【问题标题】:Unable to access the DOM using WPF WebBrowser component无法使用 WPF WebBrowser 组件访问 DOM
【发布时间】:2021-02-02 15:19:45
【问题描述】:

我正在使用以下代码访问网页的 DOM。我正在使用 WPF WebBrowser 组件(不是根据某些帖子可以正常工作的 WinForms 组件)。但是使用 WPF WebBrowser 组件,我无法弄清楚。我正在引用 mshtml 程序集,根据 this one 之类的一些帖子,我应该可以访问 DOM。但是当我在调试期间将鼠标悬停在 doc 变量上时,它会显示一个令人困惑的“System._ComObject”值。我的目标是突出显示 DOM 中的搜索词,但无法访问它。

            IHTMLDocument2 doc = WebBrowserComponent.Document as IHTMLDocument2;
            if (doc != null)
            {
                StringBuilder html = new StringBuilder(doc.body.outerHTML);

                var words = SearchWords;
                foreach (String key in words)
                {
                    String substitution = "<span style='background-color: rgb(255, 255, 0);'>" + key + "</span>";
                    html.Replace(key, substitution);
                }
                doc.body.innerHTML = html.ToString();
            }

【问题讨论】:

  • 您应该将Document 属性转换为正确的COM 接口或使用InvokeScript 方法
  • @PavelAnikhouski 这不是我已经在我的代码中做的吗?我将其转换为 IHTMLDocument2。否则,我需要有关您的建议的更多详细信息。不知道你的意思。

标签: c# wpf visual-studio-2017 mshtml


【解决方案1】:

我添加了一个按钮来突出显示引用您的代码的项目: XAML 代码:

 <StackPanel>
    <Button Content="HightLight" Click="Button_Click"> </Button>
    <WebBrowser x:Name="webBrowser" Source="https://www.bing.com/" Width="800" Height="380"/>
</StackPanel>

cs代码为:

  private void Button_Click(object sender, RoutedEventArgs e)
    {
        IHTMLDocument2 doc = webBrowser.Document as IHTMLDocument2;
        if (doc != null)
        {
            StringBuilder html = new StringBuilder(doc.body.outerHTML);
            dynamic document = webBrowser.Document;
            string str =  document.getElementById("sb_form_q").value;
            var words = new[] { str,"Bing" };
            foreach (String key in words)
            {
                String substitution = "<span style='background-color: rgb(255, 255, 0);'>" + key + "</span>";
                html.Replace(key, substitution);
            }
            doc.body.innerHTML = html.ToString();
            document.getElementById("sb_form_q").value = str;
        }
    }

结果图片如下: 我无法重现错误,你能告诉我我错过了哪一步吗?

【讨论】:

    猜你喜欢
    • 2017-07-18
    • 2012-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-21
    • 2018-12-03
    • 2014-06-22
    相关资源
    最近更新 更多