批改狀態(tài):合格
老師批語:學(xué)習(xí)可以, 數(shù)據(jù)不要用作其它用途
正則表達(dá)式:獲取京東的 列表和詳情
<?php $url = 'https://search.jd.com/Search?keyword=冰箱&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&wq=冰箱&stock=1&page=3&s=55&click=0'; $ret = curl($url); $params = '/^/'; $preg = preg_match($params,$ret,$matches); var_dump($preg); $content = $matches[1].'</div>'; $content = $matches[1].'</div>'; // 把來源網(wǎng)站的圖片標(biāo)識(shí),替換為HTML標(biāo)識(shí) $content = preg_replace('/data-original/','src',$content); $content = preg_replace('/<div id="shortcut-2014">/','src',$content); print_r($matches); print_r($ret); // 通過curl請求接口 function curl($url, $params = false, $ispost = 0) { header('content-type: text/html; charset=utf-8'); $httpInfo = array(); $ch = curl_init(); if ($ispost) { curl_setopt($ch, CURLOPT_POST, true); // 發(fā)送一個(gè)常規(guī)的Post請求 curl_setopt($ch, CURLOPT_POSTFIELDS, $params); // Post提交的數(shù)據(jù)包 curl_setopt($ch, CURLOPT_URL, $url); // 設(shè)置URL } else { // GET請求,組裝url if ($params) { $url = $url . '?'; foreach ($params as $k => $v) { $url = $url . $k . '=' . $v . '&'; } curl_setopt($ch, CURLOPT_URL, $url); } else { curl_setopt($ch, CURLOPT_URL, $url); } } curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);//爬取重定向頁面 curl_setopt($ch, CURLOPT_AUTOREFERER, 1);//自動(dòng)設(shè)置Referer,防止盜鏈 curl_setopt($ch, CURLOPT_HEADER, 0);//顯示放回Header區(qū)域內(nèi)容 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);//對證書來源的檢查 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);//從證書中檢查SSL加密算法是否存在 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);// 要求結(jié)果保存到字符串中還是輸出到屏幕上 curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); // 默認(rèn)值,讓 cURL 自己判斷使用哪個(gè)版本。 (強(qiáng)制使用 HTTP/1.1)。 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60); // 在嘗試連接時(shí)等待的秒數(shù)。設(shè)置為0,則無限等待。 curl_setopt($ch, CURLOPT_TIMEOUT, 30); // 設(shè)置超時(shí)限制防止死循環(huán) curl_setopt($ch, CURLOPT_USERAGENT, 'JuheData'); // 在HTTP請求中包含一個(gè)"User-Agent:"頭的字符串 $html = curl_exec($ch); // 運(yùn)行Curl,請求URL ,把結(jié)果復(fù)制給變量 if (curl_error($ch)) { echo 'Error' . curl_error($curl); // 捕抓異常 } curl_close($ch); // 關(guān)閉cURL連接 return $html; } ?>
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號