c#爬虫爬取京东的商品信息

2020-01-05 09:57:08王旭

获取所有商品的信息分为两个步骤

    (1)根据商品分类页面获取所有商品分类的URL

    (2)根据商品分类URL获取每个商品

 1、获取商品分类


try
{
 string html = HttpHelper.DownloadUrl(@"http://www.easck.com/allSort.aspx");
 HtmlDocument doc = new HtmlDocument();
 doc.LoadHtml(html);
 string goodClass= @"//*[@class='items']/dl/dd";
 HtmlNodeCollection noneNodeList = doc.DocumentNode.SelectNodes(goodClass);
 foreach (var node in noneNodeList)
 {
 HtmlDocument docChild = new HtmlDocument();
 docChild.LoadHtml(node.OuterHtml);
 string urlPath = "/dd/a";
 HtmlNodeCollection list = docChild.DocumentNode.SelectNodes(urlPath);
 foreach (var l in list)
 {
  HtmlDocument docChild1 = new HtmlDocument();
  docChild1.LoadHtml(l.OuterHtml);
  var sortUrl = l.Attributes["href"].Value;
  if (!string.IsNullOrWhiteSpace(sortUrl) && sortUrl.Contains("cat="))
  {
  InsertSort("https:" + sortUrl);
  }
 }
 }
}
catch (Exception ex)
{
 Console.WriteLine(ex.Message);
}

上面的代码中使用到了HtmlAgilityPack来解析HTML信息,这是.NET的开源项目,开源在nuget包中下载。

      (1)下载http://www.easck.com/allSort.aspx的html页,然后加载到HtmlDocument

      (2)选择节点,获取每个大类的节点集合

      (3)根据每个大类的节点,获取每个小类的节点信息,然后获取到分类地址

节点中也包含了其它很多信息,可以根据自己的需求去获取对应的信息