2014-04-14 91 views
0

我正在尋找一種在運行PHP爬蟲時自動切換IP的解決方案。我有一個自定義爬行程序,可以運行100個線程,但由於節流限制,我經常被阻止。由於PHP不支持多線程,因此我設置了Windows調度程序來並行運行PHP應用程序。通過PHP爬蟲進行IP交換

我想爲每個線程分配不同的IP地址,並歡迎任何解決此問題的建議。

+0

很難說如何讓你的代碼町因爲你不知道你的代碼是什麼樣的,所以有一個不同的網絡接口。它使用Curl嗎? PHP流? pecl_http? –

+0

我沒有使用任何的抓取器庫。我打算使用cURL爲每個線程切換IP,但不知道如何編程,如果這是一個正確的解決方案。 – user3084097

+0

那麼,如果你還沒有想出基本的xD,那麼就沒有必要去問如何完成複雜的任務 –

回答

2

多線程,可以在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或其他魔法使用爲線程設置的接口。

延伸閱讀: