无法使用WPF WebBrowser组件访问DOM

问题描述

我正在使用以下代码访问网页的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();
            }

解决方法

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

spring.datasource.url=jdbc:h2:mem:testdb;MODE=MySQL;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=sa
spring.datasource.password=

cs代码是:

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

结果图如下: enter image description here 我无法重现错误,您能告诉我我错过了哪一步吗?