C# 不使用浏览器控件从字符串获取HtmlDocument
我使用WebClient获取网页的html代码(作为字符串) 但是,我想将它转换为一个HtmlDocument对象,这样我就可以使用这个类提供的DOM特性。目前我知道的唯一方法是使用浏览器控件,如下所示:C# 不使用浏览器控件从字符串获取HtmlDocument,c#,browser,dom,C#,Browser,Dom,我使用WebClient获取网页的html代码(作为字符串) 但是,我想将它转换为一个HtmlDocument对象,这样我就可以使用这个类提供的DOM特性。目前我知道的唯一方法是使用浏览器控件,如下所示: string pageHtml = client.DownloadString(url); browser.ScriptErrorsSuppressed = true; browser.DocumentText = p
string pageHtml = client.DownloadString(url);
browser.ScriptErrorsSuppressed = true;
browser.DocumentText = pageHtml;
do
{
Application.DoEvents();
} while (browser.ReadyState != WebBrowserReadyState.Complete);
return browser.Document;
还有别的方法吗?我知道还有其他浏览器控件可用,但有没有更简单的方法?您可以使用。。。。例如:
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
var results = doc.DocumentNode
.Descendants("div")
.Select(n => n.InnerText);
我知道这是一个老帖子,但我的回复是给像我一样来到这里的人的 如果您想使用code.NET进行此操作
我知道这是一个老话题,我的解决方案:
public static class HtmlHelpr{
public static HtmlDocument HtmlDocumentFromFile(this string PathToHtml){
using(WebBrowser wb = new WebBrowser()){
string s = File.ReadAllText(PathToHtml);
wb.ScriptErrorsSuppressed = true;
wb.DocumentText = s;
var hd = wb.Document;
hd.Write(s);
return hd;
}
}
}
我会考虑这一点,但是我已经有很多使用HTMLDox类的代码,而且我更希望在不需要改变所有东西的情况下插入插件。
public static class HtmlHelpr{
public static HtmlDocument HtmlDocumentFromFile(this string PathToHtml){
using(WebBrowser wb = new WebBrowser()){
string s = File.ReadAllText(PathToHtml);
wb.ScriptErrorsSuppressed = true;
wb.DocumentText = s;
var hd = wb.Document;
hd.Write(s);
return hd;
}
}
}