HtmlAgilityPack 抓取论坛帖子的图片
HtmlAgilityPack
.net处理html页面元素的工具类(HtmlAgilityPack.dll)的使用,用途比较多的应该是例如采集类的功能,采集到的html字符串要怎样处理是一个头痛的问题,如果是截取就太麻烦了而且容易出错。所有就用到本文的第三方dll来处理了。
HtmlAgilityPack 下载地址
官方地址:http://htmlagilitypack.codeplex.com/
修改支持中文的地址:https://files.cnblogs.com/jak-black/HtmlAgilityPack_%E6%94%AF%E6%8C%81%E4%B8%AD%E6%96%87.7z
Demo说明:抓取帖子里面的图片,下载到本地。
核心代码
1 /// <summary> 2 /// 获取帖子列表 3 /// </summary> 4 /// <param name="url">网址</param> 5 /// <param name="nextpagstr">返回下一页的网址,没有的话将返回""</param> 6 /// <returns></returns> 7 private List<String> GetPostsList(String url) 8 { 9 List<String> iRet = new List<string>(); 10 HtmlWeb iWeb = new HtmlWeb(); 11 SetMsg("开始获取帖子列表……"); 12 for (int i = 0; i <1; i++)//控制读取论坛的链接 13 { 14 HtmlAgilityPack.HtmlDocument iHtmlDoc = iWeb.Load(url.Replace("&page=1", "&page="+(i+1))); 15 HtmlNode navNode = iHtmlDoc.GetElementbyId("threadlist"); 16 HtmlNodeCollection iNodes = navNode.SelectNodes("//ul[@class='ml mlt mtw cl']/li/h3/a");//获取UL->li-->h3-->a 17 HtmlNodeCollection imgNode = navNode.SelectNodes("//ul[@class='ml mlt mtw cl']/li/div[@class='c cl']/a");//获取UL->li-->h3-->a 18 string title = string.Empty; 19 string href = string.Empty; 20 string img = string.Empty; 21 for (int j = 0; j < iNodes.Count; j++) 22 { 23 title = iNodes[j].InnerText;//获取文字 24 href = iNodes[j].Attributes["href"].Value;//获取href 的value 25 img = imgNode[j].ChildNodes[1].Attributes["src"] == null ? "" : imgNode[j].ChildNodes[1].Attributes["src"].Value; //获取src 26 // iRet.Add("title-->" + title + " " + "href-->" + href + " " + "img-->" + img+" "); 27 iRet.Add(href); 28 } 29 SetMsg("第"+(i+1)+"页"+" 共 " + iRet.Count.ToString() + " 个帖子……"); 30 Thread.Sleep(1000); 31 } 32 return iRet; 33 } 34 35 /// <summary> 36 /// 保存文件 37 /// </summary> 38 public void GetImg() 39 { 40 List<String> li = GetPostsList(aBaseUrl); 41 for (int j = 0; j < li.Count; j++) 42 { 43 List<String> iPostsList = GetImgList(li[j].ToString()); 44 for (int i = 0; i < iPostsList.Count; i++) 45 { 46 SetMsg((i+1) + "-------------------------"); 47 string iPostid = iPostsList[i].Substring(iPostsList[i].LastIndexOf("/") + 1); 48 String aFileName = aFileBasePath + iPostid; 49 aWebClient.DownloadFile(iPostsList[i], aFileName);//下载文件 50 Thread.Sleep(1000); 51 } 52 } 53 }
浙公网安备 33010602011771号