在PHP網頁爬蟲中處理異常請求,可以通過以下幾個步驟實現:
function getUrlContent($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 如果目標URL是HTTPS,禁用SSL證書驗證
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); // 設置連接超時時間(秒)
curl_setopt($ch, CURLOPT_TIMEOUT, 10); // 設置請求超時時間(秒)
$content = curl_exec($ch);
$error = curl_error($ch);
if ($error) {
echo "Error: $error";
return null;
}
curl_close($ch);
return $content;
}
錯誤處理:在上述示例中,我們使用curl_error()
函數檢查cURL請求是否發生錯誤。如果有錯誤,我們可以輸出錯誤信息并采取適當的措施,例如記錄錯誤或跳過異常請求。
限制請求速率:為了避免對目標服務器造成過大壓力,可以限制爬蟲的請求速率??梢允褂?code>sleep()函數在每次請求之間添加延遲。
function crawlWithRateLimit($urls, $delay = 1) {
foreach ($urls as $url) {
$content = getUrlContent($url);
// 處理內容...
sleep($delay); // 添加延遲
}
}
curl_setopt($ch, CURLOPT_PROXY, 'http://proxy.example.com:8080');
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3');
通過遵循這些步驟,您可以創建一個健壯的PHP網頁爬蟲,能夠處理異常請求并適當地響應。