【问题标题】:Useragent in PHP scraper scriptPHP刮板脚本中的用户代理
【发布时间】:2011-06-19 13:56:16
【问题描述】:

我有一个 PHP 抓取脚本,用于抓取我网站上的页面。然后该脚本将内容解析为 HTML 并将其输出给用户。我偶然发现在 PHP 中使用 useragent 函数来假装你是一个爬虫,例如 GoogleBot。如何将我的两个脚本组合在一起,以便我正在抓取的页面认为我是爬虫?

我的爬虫 PHP 代码是:

$query=$_REQUEST['q'];

$html = file_get_contents("search.php?q=$query");
preg_match_all(
    '/<div class="cl1 cld">.*?<a rel="nofollow" class="l le" href="(.*?)">(.*?)<\/a>.*?<div class="cra">(.*?)<\/div>.*?<div class="clud">(.*?)<\/div>.*?<\/div>/s',
    $html,
    $posts, // will contain the blog posts
    PREG_SET_ORDER // formats data into an array of posts
);

foreach ($posts as $post) {
    $link = $post[1];
    $title = $post[2];
    $description = $post[3];
    $url = $post[4];

echo "<div class='result'><div class='title'><a href='$link'>$title</a></div>$description<div class='url'>$url</div></div>";
}

?>

我有这行伪装成爬虫的代码。

$userAgent = 'MyScraperBot (http://www.mysite.com/)';

【问题讨论】:

    标签: php


    【解决方案1】:

    如果你想继续使用file_get_contents,你可以设置PHPs internal(http fopen wrapper)用户代理:

     ini_set("user_agent", 'MyScraperBot (http://www.mysite.com/)');
    

    【讨论】:

    • 在文件顶部,在 file_get_contents 调用之前。
    • 在您发送任何文件请求之前。
    • 它将显示在日志文件中。如果该网站管理员检查用户代理的访问日志,那么这就是他将看到的内容。
    • 是的,这是您可以伪装成的用户代理列表:user-agents.org
    • 它将显示为您将 user_agent 值设置为的任何值,但如果您尝试成为特定的机器人,那么该列表将为您提供正确的值。
    【解决方案2】:

    你需要使用 CURL setopt

    // spoofing FireFox 2.0
    $useragent="Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1";
    
    $ch = curl_init();
    
    // set user agent
    curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
    // set the rest of your cURL options here
    

    【讨论】:

    • 放任何你想要的用户代理,就像你自己的一样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-26
    • 1970-01-01
    • 1970-01-01
    • 2017-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多