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

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

前言

在一个小项目中,需要用到京东的所有商品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