C#使用HtmlAgilityPack快速爬虫

HtmlAgilityPack真是一把网抓利器,可以迅速地从网页抓到想要的文本或数据,使用起来十分方便,引用时在NuGet安装添加并在头部引用using HtmlAgilityPack;即可。

针对网址直接使用Load方法:

HtmlWeb webc = new HtmlWeb();
HtmlDocument htmlDoc = webc.Load(@"https://doc。。。");
HtmlNodeCollection hc = htmlDoc.DocumentNode.SelectNodes("//td[contains(normalize-space(text()),'Investment Advisor:')]/../../../../preceding-sibling::div[position()<=3]");

如果需要读取的html文档是本地的,可以先获取数据流,再使用LoadHtml方法:

FileStream fs = new FileStream(@"C:\Users\jlin10\Desktop\test.html", FileMode.OpenOrCreate, FileAccess.Read);
StreamReader sr = new StreamReader(fs, Encoding.Default);
string htmlstr = sr.ReadToEnd();
sr.Close();
fs.Close();
HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
htmlDoc.LoadHtml(htmlstr);

抓出来之后就可以对hc循环取innertext属性得到结果,不过HtmlAgilityPack的selectnode(s)方法只支持xpath,不支持jsoup,所以要准确地抓出想要的东西就得看xpath写得好不好了,这里推荐下使用xpath常用的两个网址:

https://www.cnblogs.com/VseYoung/p/8686383.html

http://www.w3school.com.cn/xpath/xpath_functions.asp

上面代码中使用的HTML文档测试例子

 

posted @ 2019-06-03 19:50  微时空  阅读(1442)  评论(0编辑  收藏  举报