php爬取天猫和淘宝商品数据

一、思路

最近做了一个网站用到了从网址爬取天猫和淘宝的商品信息,首先看了下手机端的网页发现用的react,不太了解没法搞,所以就考虑从PC入口爬取数据,但是当爬取URL获取数据时并没有获取价格,库存等的信息,仔细研究了下发现是异步请求了另一个接口,但是接口要使用refer才能获取数据,于是就通过以下方式写了一个简单的爬虫,用于爬取商品预览图和商品的第一个分类的价格、库存等。

二、实现

代码如下:

  1. function crawlUrl($url){
  2. import('PhpQuery.Curl');
  3. $curl=new \Curl();
  4. $result = $curl->read($url);
  5. $content = mb_convert_encoding( $result['content'], 'UTF-8', 'UTF-8,GBK,GB2312,BIG5' );
  6. $myres=array();
  7. if(strrpos($url,'taobao.com')!=false) {
  8. //匹配是否下架
  9. if(strpos($content,'此宝贝已下架')!==false){
  10. return false;
  11. }
  12. preg_match("|itemId : '(.*)'|isU", $content, $match);
  13. $item_id=$match[1];
  14. preg_match("|sellerId : '(.*)'|isU", $content, $match);
  15. $sellet_id=$match[1];
  16. preg_match("|<title>(.*)</title>|isU",$content,$match);
  17. $title=$match[1];
  18. //价格库存信息
  19. $ch = curl_init();
  20. curl_setopt ($ch, CURLOPT_URL, 'https://detailskip.taobao.com/service/getData/1/p1/item/detail/sib.htm?item&seller&modules=dynStock,qrcode,viewer,price,duty,xmpPromotion,delivery,upp,activity,fqg,zjys,amountRestriction,couponActivity,soldQuantity,originalPrice,tradeContract&callback=onSibRequestSuccess');
  21. $opt[CURLOPT_HEADER]=false;
  22. $opt[CURLOPT_CONNECTTIMEOUT]=15;
  23. $opt[CURLOPT_TIMEOUT]=300;
  24. $opt[CURLOPT_AUTOREFERER]=true;
  25. $opt[CURLOPT_USERAGENT]='Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11';
  26. curl_setopt_array($ch,$opt);
  27. curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
  28. curl_setopt ($ch,CURLOPT_REFERER,$url);
  29. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  30. $out_put=curl_exec ($ch);
  31. curl_close ($ch);
  32. $res=str_replace('onSibRequestSuccess(',"",$out_put);
  33. $res=rtrim($res,');1');
  34. $result=json_decode($res,true);
  35. //查询出图片信息
  36. preg_match('|<ul class="tb-thumb tb-clearfix">(.*)</ul>|isU', $content, $match);
  37. preg_match_all('/<img data-src="(.*?)" \//', $match[1], $images);
  38. $myres['title']=str_replace('-淘宝网','',$title);
  39. $myres['price']=current($result['data']['originalPrice']);
  40. $myres['act_price']=current($result['data']['promotion']['promoData']);
  41. $myres['stock']=$result['data']['dynStock']['stock'];
  42. $myres['banners']=$images[1];
  43. }else{
  44. //匹配是否下架
  45. if(strpos($content,'此宝贝已下架')!==false){
  46. return false;
  47. }
  48. $start=strpos($url,'&id=');
  49. $item_id=substr($url,$start+4,12);
  50. if(!is_numeric($item_id)){
  51. $start=strpos($url,'?id=');
  52. $end=strpos($url,'&spm');
  53. $item_id=substr($url,$start+4,$end-$start-4);
  54. }
  55. preg_match("|<title>(.*)</title>|isU",$content,$match);
  56. $title=$match[1];
  57. $myurl='https://mdskip.taobao.com/core/initItemDetail.htm?cachedTimestamp=1500562177777&queryMemberRight=true&cartEnable=true&offlineShop=false&addressLevel=2&item&tryBeforeBuy=false&isAreaSell=false&tmallBuySupport=true&isPurchaseMallPage=false&household=false&isForbidBuyItem=false&service3C=false&isRegionLevel=false&showShopProm=false&isSecKill=false&sellerPreview=false&isUseInventoryCenter=false&isApparel=true&callback=setMdskip&timestamp=1500562172109&isg=AiUlDZFWmP/sMgVurQSILU3Ytet/Zdis&isg2=Ajk51JIhRFqKzxmiNPP6dkYxSKXT7iySkzSTeVtu9WDf4ll0o5Y9yKdyEtHu';
  58. //价格库存信息
  59. $ch = curl_init();
  60. curl_setopt ($ch, CURLOPT_URL, $myurl);
  61. $opt[CURLOPT_HEADER]=false;
  62. $opt[CURLOPT_CONNECTTIMEOUT]=15;
  63. $opt[CURLOPT_TIMEOUT]=300;
  64. $opt[CURLOPT_AUTOREFERER]=true;
  65. $opt[CURLOPT_USERAGENT]='Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11';
  66. curl_setopt_array($ch,$opt);
  67. curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
  68. curl_setopt ($ch,CURLOPT_REFERER,$url);
  69. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  70. $out_put=curl_exec ($ch);
  71. curl_close ($ch);
  72. $res = mb_convert_encoding( $out_put, 'UTF-8', 'UTF-8,GBK,GB2312,BIG5' );
  73. $res=str_replace('setMdskip',"",$res);
  74. $res=str_replace('(',"",$res);
  75. $res=str_replace(')',"",$res);
  76. $result=json_decode($res,true);
  77. $nowk="";
  78. $nowstore="";
  79. foreach($result['defaultModel']['inventoryDO']['skuQuantity'] as $k=>$val){
  80. $nowk=$k;
  81. $nowstore=$val;
  82. break;
  83. }
  84. $myres['title']=str_replace('-tmall.com天猫','',$title);
  85. $myres['price']=$result['defaultModel']['itemPriceResultDO']['priceInfo'][$nowk]['price'];
  86. $myres['act_price']=isset($result['defaultModel']['itemPriceResultDO']['priceInfo'][$nowk]['suggestivePromotionList'])?$result['defaultModel']['itemPriceResultDO']['priceInfo'][$nowk]['suggestivePromotionList']:$result['defaultModel']['itemPriceResultDO']['priceInfo'][$nowk];
  87. $myres['stock']=$result['defaultModel']['inventoryDO']['totalQuantity']?$result['defaultModel']['inventoryDO']['totalQuantity']:$nowstore['quantity'];
  88. //查询出图片信息
  89. preg_match('|<ul class="tb-thumb tm-clear">(.*)</ul>|isU',$content, $match);
  90. preg_match_all('/<img src="(.*?)" \//',$match[1],$images);
  91. $myres['banners']=$images[1];
  92. }
  93. return $myres;
  94. }

上述代码用到phpquery的库,但是其实没啥用,直接用Curl就行,具体爬取的数据可以穿参查看结果,方法不区分淘宝和天猫链接,但是前提是必须是PC端链接,另外正则写的不规范,所以可以自己重写正则来匹配数据。