人。关于正在编写的脚本,我需要一些帮助。
我想要做的是对File_get_content请求使用代理,但是处于循环状态。我正在分享一个基本示例,说明我正在努力实现的目标。这不是实际的脚本,只是一个基本示例。
假设我有txt文件名“ urls_to_scrape.txt”和txt文件“ proxy_list.txt”。
urls_to_scrape.txt 将包含以行分隔的URL列表。
http://example1.com
http://example2.com
http://example3.com
http://example4.com
.... so far arround 50k more.
proxy_list.txt 将包含以行分隔的代理列表。
proxy1:port
proxy2:port
proxy3:port
proxy4:port
但是主要技巧是每个代理只能请求3次。代理使用3次后,脚本将移至下一个代理。一旦使用了所有代理。脚本将从头开始再次使用代理,直到所有URL都完整。
这是我到目前为止写的。
/* Get the list as array then start the loop */
foreach ( file ( "urls_to_scrape.txt" ) as $url ) {
//Trim it to remove spaces.
$url = trim ( $url );
$headers = array(
"http" => array(
'proxy' => 'tcp://'.$proxy.'',
'request_fulluri' => true,
'user_agent' => 'Mozilla/5.0 (X11; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0',
'timeout' => 10
)
);
$context = stream_context_create( $headers );
$content = file_get_contents( $url, false, $context );
}
如您所见,$ proxy字符串为空。。我无法编写代理逻辑。我如何让脚本从列表中知道要使用代理,但是每个代理 3次。一旦代理使用了 3次,脚本将使用列表中的下一个代理。使用完所有代理后,脚本将从头开始再次使用代理。
答案 0 :(得分:0)
您可以使用2个变量,例如$proxyNumber
和$useCount
。
在循环中,检查$useCount
是否达到3,如果达到3,则将其分配为0,然后将1加到$proxyNumber
在循环外初始化文件,并在每个请求中向$useCount
加1。
那会是这样的:
//Initialize variables
$proxyNumber = 0;
$useCount = 0;
$proxyList = file("proxy_list.txt");
foreach ( file ( "urls_to_scrape.txt" ) as $url ) {
if($useCount === 3){ //Check if it have been used 3 times
if($proxyNumber === count($proxyList)-1) {//Restart at end of the file
$proxyNumber = 0;
}else{ //else go to next
$proxyNumber += 1;
}
$useCount = 0; //Restart number of uses to 0
}
$proxy = $proxyList[$proxyNumber];
$proxy = trim($proxy); //Trim the proxy
//Trim it to remove spaces.
$url = trim ( $url );
print "$url using $proxy<br />"; // This is for debug purposes only, you can remove it
$useCount += 1; //Set this after $proxy have been set
$headers = array(
"http" => array(
'proxy' => 'tcp://'.$proxy.'',
'request_fulluri' => true,
'user_agent' => 'Mozilla/5.0 (X11; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0',
'timeout' => 10
)
);
$context = stream_context_create( $headers );
$content = file_get_contents( $url, false, $context );
}
调试应返回如下内容:
http://example1.com using proxy1:port
http://example2.com using proxy1:port
http://example3.com using proxy1:port
http://example4.com using proxy2:port
http://example5.com using proxy2:port
http://example6.com using proxy3:port
http://example7.com using proxy3:port
http://example8.com using proxy4:port
http://example9.com using proxy4:port
http://example10.com using proxy1:port