尝试使用 cURL 抓取网页的 HTML 内容时cURL,经常会遇到重定向或“页面移动”错误。这通常可以归因于查询字符串中特殊编码的字符。
要有效检索页面内容而不遇到这些问题,请按如下方式优化 cURL 代码:
<code class="php">function get_web_page($url) { $user_agent='Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0'; $options = array( CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_POST => false, CURLOPT_USERAGENT => $user_agent, CURLOPT_COOKIEFILE => "cookie.txt", CURLOPT_COOKIEJAR => "cookie.txt", CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => false, CURLOPT_FOLLOWLOCATION => true, CURLOPT_ENCODING => "", CURLOPT_AUTOREFERER => true, CURLOPT_CONNECTTIMEOUT => 120, CURLOPT_TIMEOUT => 120, CURLOPT_MAXREDIRS => 10, ); $ch = curl_init($url); curl_setopt_array($ch, $options); $content = curl_exec($ch); $err = curl_errno($ch); $errmsg = curl_error($ch); $header = curl_getinfo($ch); curl_close($ch); $header['errno'] = $err; $header['errmsg'] = $errmsg; $header['content'] = $content; return $header; }</code>
在阅读页面时检索并处理潜在错误:
<code class="php">$result = get_web_page($url); if ($result['errno'] != 0) // Error handling for invalid URL, timeout, or redirect loops. if ($result['http_code'] != 200) // Error handling for issues like missing page, permission denial, or unavailability. $page = $result['content'];</code>
以上是如何使用带有错误处理的 cURL 高效提取页面内容?的详细内容。更多信息请关注PHP中文网其他相关文章!