【问题标题】:IP switching over PHP crawlerPHP爬虫IP切换
【发布时间】:2014-05-28 08:56:08
【问题描述】:

我正在寻找一种在运行 PHP 爬虫时自动切换 IP 的解决方案。我有一个定制的爬虫,它运行 100 个线程,但由于油门限制,我经常被阻塞。由于 PHP 不支持多线程,我设置了 windows 调度程序来并行运行 PHP 应用程序。

我想为每个线程分配不同的 IP 地址,并欢迎任何解决此问题的建议。

【问题讨论】:

  • 很难说如何让你的代码选择不同的网络接口,因为你不知道你的代码是什么样子的。它使用卷曲吗? PHP流? pecl_http?
  • 我没有为爬虫使用任何库。我计划使用 cURL 为每个线程切换 IP,但不知道如何编程以及这是否是正确的解决方案。
  • 好吧,如果你还没有弄清楚基础知识,那么问如何完成复杂的任务是没有意义的 xD

标签: php multithreading proxy ip web-crawler


【解决方案1】:

PHP 支持多线程

有些人甚至会说它微不足道……

<?php
define('LOG', Mutex::create());

/* make output when writing to stdout thread safe (so, readable) */
function slog($message, $args = []) {
    $args = func_get_args();
    if (($message = array_shift($args))) {
        Mutex::lock(LOG);
        echo vsprintf($message, $args);
        Mutex::unlock(LOG);
    }
}

class WebCrawler extends Thread {

    public function __construct($interface) {
        $this->interface = $interface;
    }

    public function run() {
        slog("Thread %lu using %s\n", 
            $this->getThreadId(), $this->getInterface());
    }

    public function getInterface() { 
        return $this->interface; 
    }

    protected $interface;
}

$interfaces = [
    "192.168.0.1",
    "192.168.0.2",
    "192.168.0.3",
    "192.168.0.4",
    "192.168.0.5"
];

$threads = [];
$thread = 0;
while (count($threads) < count($interfaces)) {
    $threads[$thread] = new WebCrawler($interfaces[$thread]);
    $threads[$thread]->start();
    $thread++;
}

foreach ($threads as $thread)
    $thread->join();

Mutex::destroy(LOG);
?>

上面的代码从预定义的接口列表中为每个线程提供了一个接口。然后,您将配置您的客户端使用 CURLOPT_INTERFACE 或其他一些魔法为线程设置的接口。

进一步阅读:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-24
    • 2014-05-24
    • 2019-11-07
    • 2015-09-22
    • 2011-08-03
    • 1970-01-01
    相关资源
    最近更新 更多