我正在使用WebClient.DownloadString(url)
通过URL获取HTML文档,但很难找到我要查找的元素内容。在阅读相关文章时,我注意到了HtmlDocument
及其具有的诸如GetElementById
之类的便捷功能。如何使用由url
返回的HTML填充HtmlDocument
?
使用Html Agility Pack,如SLaks所建议的那样,这变得非常简单:
string html = webClient.DownloadString(url);
var doc = new HtmlDocument();
doc.LoadHtml(html);
HtmlNode specificNode = doc.GetElementById("nodeId");
HtmlNodeCollection nodesMatchingXPath = doc.DocumentNode.SelectNodes("x/path/nodes");
HtmlDocument
类是对本地 IHtmlDocument2
COM 接口的封装。
无法直接通过字符串轻松创建它。
应该使用 HTML Agility Pack。
HTMLDocument doc = new HTMLDocument();
IHTMLDocument2 doc2 = (IHTMLDocument2)doc;
doc2.write(fileText);
// now use doc
然后将其转换回字符串:
doc.documentElement.outerHTML;
HTMLDocument
。 - Steinfeldmshtml;
。在引用对话框中它是 Microsoft.mshtml
。我正在使用版本 7.0.3300
。 - David Sherretabout:blank
页面。 - hillin如果您不想使用HTML Agility Pack,并且只想使用本地的.NET代码从字符串中获取HtmlDocument,则可以参考这篇文章如何将字符串转换为HtmlDocument
以下是可用的代码块
public System.Windows.Forms.HtmlDocument GetHtmlDocument(string html)
{
WebBrowser browser = new WebBrowser();
browser.ScriptErrorsSuppressed = true;
browser.DocumentText = html;
browser.Document.OpenNew(true);
browser.Document.Write(html);
browser.Refresh();
return browser.Document;
}
我对Nikhil的回答进行了一定程度的改编,以简化它。不可否认,我没有通过.net编译器运行它,而Nikhil放置的几行代码可能有非常好的原因,但是至少在我的用例中(一个非常简单的页面),它们是不必要的。
我的用例是为了快速编写powershell脚本:
$htmlText = $(New-Object
System.Net.WebClient).DownloadString("<URI HERE>") #Get the HTML document from a webserver
$browser = New-Object System.Windows.Forms.WebBrowser
$browser.DocumentText = $htmlText
$browser.Document.Write($htmlText)
$response = $browser.document
HTMLElement
对象的HTMLDocument
对象,而不是在PS 5.1.14393.1944中由调用Invoke-WebRequest
返回的__ComObject
对象类型(这些类型在powershell类代码中使用起来很具有挑战性)。public System.Windows.Forms.HtmlDocument GetHtmlDocument(string html)
{
WebBrowser browser = new WebBrowser();
browser.DocumentText = html;
browser.Document.Write(html);
return browser.Document;
}
您可以通过以下方式获取HTML文档:
System.Net.WebClient wc = new System.Net.WebClient();
System.IO.Stream stream = wc.OpenRead(url);
System.IO.StreamReader reader = new System.IO.StreamReader(stream);
string s = reader.ReadToEnd();
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(s);
你已经有了getbiyid和getbyname...但是如果需要更深入的操作,建议使用HTML Agility Pack。例如:你可以使用doc.DocumentNode.SelectNodes(xpathselector)或者正则表达式解析文档。
顺便问一下:为什么不用正则表达式?如果你能正确使用它,它非常酷。但是xpath也非常强大。所以“选择你的毒药”。
再见
HtmlDocument
在哪个命名空间中?我正在使用System.Windows.Forms.HtmlDocument
,但没有LoadHtml()
方法。 - Scott BakerHtmlAgilityPack.HtmlDocument
。 - C4d