C# 爬虫 爬取拼多多商品信息

根据拼多多搜索关键字爬取拼多多商品信息,如果没有登录,同一网络爬取信息,最多可以爬取1~3次,你爬取之后你再次搜索就需要登录,但有一个时间限制(这个没有测试,估计1h后就会解封,就可以再次爬取),而且你切换网络,也可以再次爬取,这个是没有问题的。当然,你也可以的登录之后爬取,这样可以爬取N次,只有没有被封号(但这是不可能的)

拼多多爬取商品信息,每次会返回   20条商品信息,他是放在一个HTML页面,通过JS渲染上去的。就是这个API (https://mobile.yangkeduo.com/search_result.html?search_key=%E5%8D%8E%E4%B8%BA%E6%89%8B%E6%9C%BA&search_type=goods&source=index&options=3&search_met_track=manual&refer_page_el_sn=99884&refer_page_name=search_result&refer_page_id=10015_1615777503796_4wmnbjg2ck&refer_page_sn=10015)  
search_key 后面就是你的搜索的关键字。 还有 这个API的 get 请求。

代码如下

public void GetShopList(string shopName){
  #region 获取html
  string url = "https://mobile.yangkeduo.com/search_result.html?search_key=" + shopName+ "&search_type=goods&source=index&options=1&search_met_track=manual&refer_page_el_sn=99885&refer_page_name=search_result&refer_page_id=10015_1615453872480_bba38nr834&refer_page_sn=10015";
  RestRequest request = new RestRequest(url);
  request.Method = Method.GET;
  IRestResponse response = restClient.Execute(request);
  #endregion
  if (!response.IsSuccessful) return false;
  if (response.Content.Contains("window.rawData=null")) {
    Console.WriteLine("获取失败");     
    return false;
   }
   string shopList=response.Content
  analysis(shopList)
}
shoping 是商品关键字。
response.Content:就是商品的信息页面,然后response.Content 后面的JS里面有个 window.rawData=,然后  window.rawData=null  说明这时你的ip暂时被封了如果是这样的数据,说明数据获取成功。


public void analysis(string shopList){
  #region 解析html 
  HtmlDocument htmlDocument = new HtmlDocument();
  htmlDocument.LoadHtml(content);
  var node1 = htmlDocument.DocumentNode.
  SelectNodes(@"//script");
  if (node1 is null) throw new Exception("Can not find id: __VIEWSTATE"); 
  #endregion
  foreach (var de in node1)
  {
   if (de.InnerHtml.Contains("window.rawData"))
   {
      string data = de.InnerText;
      data = System.Text.RegularExpressions.Regex.Split(data, "window.rawData=")[1];
      data = data.Substring(0, data.Length - 1);
      JsonData deJson = LitJson.JsonMapper.ToObject(data);
      deJson = deJson["store"]["listData"]["list"];                 
      for (int num_hisEQ = 0; num_hisEQ < deJson.Count; num_hisEQ++){
        string key=deJson[num_hisEQ]["key"].ToString();
        ………………
      }
    }
 }         
然后需要解析获取的string,需要Nuget 里面下载  HtmlAgilityPack 和 LitJson  这两个包。这样就可以搞定了。

原文地址:https://www.cnblogs.com/my1227/p/14536823.html