如何从 WPF WebBrowser 获取 HtmlElementCollection

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29972874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 13:06:40  来源:igfitidea点击:

How can I get an HtmlElementCollection from a WPF WebBrowser

c#wpfc#-4.0html-agility-packhtmlelements

提问by software is fun

My old WinForm application used HtmlElementCollection to process a page

我的旧 WinForm 应用程序使用 HtmlElementCollection 处理页面

HtmlElementCollection hec = this.webbrowser.Document.GetElementsByTagName("input");

In WPF WebBrowser, there are several things that are different. For example

在 WPF WebBrowser 中,有几个不同的地方。例如

this.webbrowser.Documentdoes not have any method called GetElementsByTagName

this.webbrowser.Document没有任何名为GetElementsByTagName 的方法

Therefore my code is unable to get an HtmlElementCollection

因此我的代码无法获得 HtmlElementCollection

回答by dkozl

You need to add reference to Microsoft.mshtmland then you need to cast document as mshtml.HTMLDocument. After you do that you should be able to use getElementsByTagName()method

您需要添加对的引用Microsoft.mshtml,然后需要将文档转换为mshtml.HTMLDocument. 在你这样做之后,你应该能够使用getElementsByTagName()方法

 var document = webBrowser.Document as mshtml.HTMLDocument;
 var inputs = document.getElementsByTagName("input");
 foreach (mshtml.IHTMLElement element in inputs)
 {

 }

getElementsByTagName()returns mshtml.IHTMLElementCollectionand each item is of a mshtml.IHTMLElementtype

getElementsByTagName()返回mshtml.IHTMLElementCollection并且每个项目都是一种mshtml.IHTMLElement类型

EDIT

编辑

Alternative solution, if you need to use WinForms WebBrowseryou can use that instead of the WPF one. Add reference to WindowsFormsIntegrationand System.Windows.Forms, create namespace in XAML and use different browser control

另一种解决方案,如果您需要使用 WinForms,WebBrowser您可以使用它而不是 WPF。添加对WindowsFormsIntegrationand 的引用System.Windows.Forms,在 XAML 中创建命名空间并使用不同的浏览器控件

<Window ...
    xmlns:winforms="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms">
    <WindowsFormsHost>
        <winforms:WebBrowser x:Name="webBrowser"/>
    </WindowsFormsHost>
</Window>