【发布时间】: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