【问题标题】:PHP CURL - Problems storing and using cookies when scrapingPHP CURL - 抓取时存储和使用 cookie 的问题
【发布时间】:2012-12-01 09:44:34
【问题描述】:

我一直在尝试编写一个脚本来检索给定关键字的 Google 趋势结果。请注意,我并没有试图做任何恶意的事情,我只是希望能够自动化这个过程并每天运行几次。

在调查了 Google 趋势页面后,我发现可以使用以下 URL 获得该信息:

http://www.google.com/trends/trendsReport?hl=en-GB&q=keyword&cmpt=q&content=1

您可以多次从浏览器请求该信息而不会出现问题,但如果您在 4 或 5 次请求后尝试使用“隐私模式”,则会显示以下信息:

检测到错误您已达到配额限制。请 请稍后再试。

这让我觉得 cookie 是必需的。所以我写了我的脚本如下:

$cookiefile = $siteurl . '/wp-content/plugins/' . basename(dirname(__FILE__)) . '/cookies.txt';


$url = 'http://www.google.com/trends/trendsReport?hl=en-GB&q=keyword&cmpt=q&content=1'; 
$ch = curl_init();      

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.8) Gecko/2009032609 Firefox/3.0.8');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);        
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);


$x='error';
while (trim($x) != ''  ){
     $html=curl_exec($ch);
     $x=curl_error($ch);
}

echo  "test cookiefile contents = ".file_get_contents($cookiefile)."<br />";
echo $html;

但是,我无法将任何内容写入我的 cookie 文件。所以我不断收到错误消息。谁能看出我哪里出了问题?

【问题讨论】:

  • 我在下面回答。但是谷歌有很多不让人们抓取数据的技巧。返回错误很常见,而实际上它们会阻止您。
  • 如果你小心使用 curl,除非有验证码,否则谷歌永远不会知道它是人类还是 curl。
  • $siteurl 的值是多少?这应该是文件系统路径,而不是 url。

标签: php html cookies curl web-scraping


【解决方案1】:

我很确定您的 cookie 文件应该存在,然后您才能将它与 curl 一起使用。 试试:

$h = fopen($cookiefile, "x+");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-20
    • 2011-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-18
    • 2015-03-09
    相关资源
    最近更新 更多