前言
在一个小项目中,需要用到京东的所有商品ID,因此就用c#写了个简单的爬虫。
在解析HTML中没有使用正则表达式,而是借助开源项目HtmlAgilityPack解析HTML。
下面话不多说了,来一起看看详细的介绍吧
一、下载网页HTML
首先我们写一个公共方法用来下载网页的HTML。
在写下载HTML方法之前,我们需要去查看京东网页请求头的相关信息,在发送请求时需要用到。
public static string DownloadHtml(string url, Encoding encode){ string html = string.Empty; try { HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Timeout = 30 * 1000; request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36"; request.ContentType = "text/html; charset=utf-8"; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { if (response.StatusCode == HttpStatusCode.OK) { try { StreamReader sr = new StreamReader(response.GetResponseStream(), encode); html = sr.ReadToEnd();//读取数据 sr.Close(); } catch (Exception ex) { html = null; } } } } catch (System.Net.WebException ex) { html = null; } catch (Exception ex) { html = null; } return html;}如上代码所示,我们使用WebRequest来获取网页信息,在发送请求之前,需要先设置和京东页面一样的请求头。
以上设置的信息比较简单,但能够正常发送请求,我们也可以模拟浏览器设置cookie等等信息,
二、解析HTML
获取所有商品的信息分为两个步骤
(1)根据商品分类页面获取所有商品分类的URL
(2)根据商品分类URL获取每个商品
1、获取商品分类
try{ string html = HttpHelper.DownloadUrl(@"http://modityPrice>>(html); productInfoList.ForEach(c => c.Price = priceList.FirstOrDefault(p => p.id.Equals(string.Format("J_{0}", c.ProductId))).p); } catch (Exception ex) { Console.WriteLine(ex.Message); } return productInfoList;以上就是一个简单的爬取京东商品信息的爬虫,也可以根据自己的需求去解析更多的数据出来。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。