curl抓取页面时遇到重定向的解决方法(转)

phpcurl抓取网页遇到了问题,为阐述方便,将代码简化如下:

  1. <?php  
  2. function curlGet($url) {  
  3.         $ch = curl_init();  
  4.         curl_setopt($ch, CURLOPT_URL, $url);  
  5.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);   
  6.         curl_setopt($ch, CURLOPT_HEADER, true);  
  7.         return curl_exec($ch);  
  8. }  
  9.   
  10. $url = 'http://144go.com';  
  11. echo curlGet($url), "\n";  

代码的目的很简单,抓取页面:http://www.144go.com
执行上述代码,得到的结果:

  1. HTTP/1.1 301 Moved Permanently  
  2. Content-Length: 144  
  3. Content-Type: text/html  
  4. Location: http://www.144go.com/  
  5. Server: Microsoft-IIS/6.0  
  6. X-Powered-By: ASP.NET  
  7. Date: Mon, 03 Sep 2012 04:25:22 GMT  
  8.   
  9. <head><title>Document Moved</title></head>  
  10. <body><h1>Object Moved</h1>This document may be found <a HREF="http://www.144go.com/">here</a></body>  

由结果中的
Location: http://www.144go.com/
可知http://144go.com被重定向到了http://www.144go.com/

怎么办呢,要用正则分析出Location部分的链接,重复执行执行curlGet吗?行到是行,就是有点麻烦。

其实只要加一条语就可以了:

  1. <?php  
  2. function curlGet($url) {  
  3.         $ch = curl_init();  
  4.         curl_setopt($ch, CURLOPT_URL, $url);  
  5.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);   
  6.         curl_setopt($ch, CURLOPT_HEADER, true);  
  7.         //函数中加入下面这条语句  
  8.         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);          
  9.         return curl_exec($ch);  
  10. }  

再次执行代码,可以抓取到想要的页面。
CURLOPT_FOLLOWLOCATION指明:
curl递归的抓取http头中Location中指明的url
当抓取次数超过CURLOPT_MAXREDIRS时,递归将终止。
在抓取中任何跳转带来的问题,都可通过设置此参数解决。

posted on 2016-08-01 15:08  混元真人  阅读(1364)  评论(0编辑  收藏  举报