当前位置:Gxlcms > PHP教程 > 求高手,模拟浏览器抓取网页

求高手,模拟浏览器抓取网页

时间:2021-07-01 10:21:17 帮助过:4人阅读

如抓取http://map.sogou.com/api/这个网页,我写的程序,如果不带网址后面的"/",会抓取得不到,但是站上网(http://tool.chinaz.com/Tools/PageCode.aspx),不带最后面的"/"即可抓取到(即:http://map.sogou.com/api),他是什么原理?下面贴出我的代码,请改进

  1. function file_get($url){
  2. ob_start();
  3. $ch = curl_init();
  4. curl_setopt($ch, CURLOPT_COOKIEJAR, "./cookie.txt");
  5. curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; InfoPath.1; CIBA)");
  6. curl_setopt($ch, CURLOPT_URL, $url);
  7. curl_setopt($ch, CURLOPT_HEADER, FALSE);
  8. curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
  9. curl_setopt($ch, CURLOPT_NOBODY, FALSE);
  10. curl_exec($ch);
  11. curl_close($ch);
  12. $content = ob_get_clean();
  13. return $content;}


回复讨论(解决方案)

请加一句代码:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);

因为你抓取http://map.sogou.com/api,他返回的是301跳转。加上这句就能抓取跳转后的html了。

请加一句代码:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);

因为你抓取http://map.sogou.com/api,他返回的是301跳转。加上这句就能抓取跳转后的html了。
加上也不行,还是无法获取


请加一句代码:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);

因为你抓取http://map.sogou.com/api,他返回的是301跳转。加上这句就能抓取跳转后的html了。
加上也不行,还是无法获取


  1. function file_get($url){
  2. ob_start();
  3. $ch = curl_init();
  4. curl_setopt($ch, CURLOPT_COOKIEJAR, "./cookie.txt");
  5. curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; InfoPath.1; CIBA)");
  6. curl_setopt($ch, CURLOPT_URL, $url);
  7. curl_setopt($ch, CURLOPT_HEADER, FALSE);
  8. curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
  9. curl_setopt($ch, CURLOPT_FOLLOWLOCATION,TRUE);
  10. curl_setopt($ch, CURLOPT_NOBODY, FALSE);
  11. curl_exec($ch);
  12. curl_close($ch);
  13. $content = ob_get_clean();
  14. return $content;}


我测试过的,加上是行的呀。

CURLOPT_FOLLOWLOCATION

人气教程排行