等待 CloudFlare DDOS 保护 LWP Perl

Waiting for CloudFlare DDOS Protection LWP Perl

编辑:结束使用 WWW::Mechanize::Firefox。我在下面回答了我自己的问题。

我正在尝试访问一个网站并下载它的页面。站点上的cloudflare DDOS保护偶尔会亮起,我无法让LWP通过。我可以成功检测到页面 带有正则表达式 /Ray ID: [a-f0-9]*/ 的 cloudflare 初始页面,但每当我尝试再次连接时,我只会得到相同的初始屏幕和新的 Ray ID。这是一个(浓缩的)代码示例:

use LWP::UserAgent;
$ua = LWP::UserAgent->new;
$ua->agent('Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0 Iceweasel/31.3.0');
$signin_url = 'my url';
$signin_page = $ua->get($signin_url);
if($signin_page->content =~ /Ray ID: ([a-f0-9]*)/i) {
     print "DDOS protection page here\n";
     #more code to retry, but just gets back into this part of the IF
 } else {
     print "Not the DDOS page\n";
     #now I would save to file
}

既然那行不通,我需要用另一种方式来做。

DDOS 保护拦截请求,设置 cookie,然后将您重定向到目标页面。您必须在下一次请求时提交从拦截中获得的 cookie 才能通过 DDOS 保护。如果您创建一个 cookie 罐,LWP 将为您执行此操作。

LWP::UserAgent->new( cookie_jar => {} )

WWW::Mechanize,LWP::UserAgent 的子类,为您将该参数传递给 LWP::UserAgent,因此您也可以使用

 use WWW::Mechanize;
 my $ua = WWW::Mechanize->new;

LWP::UserAgentWWW::MechanizeUA有cookie jar时,get会自动接受cookie,跟随重定向,在后续请求中提交cookie。

Cloudflare 需要 Javascript,所以我使用了 WWW::Mechanize::Firefox。像这样

#!/usr/bin/perl
use WWW::Mechanize::Firefox;
system('firefox &'); #The & makes it so the program doesn't wait.
sleep 5; #So firefox can load
$mech = WWW::Mechanize::Firefox->new;
$mech->get('http://www.mycloudflareblockedwebsite.com/');
if($mech->content =~ /Test if it is the CLOUDFLARE source HTML page/) {
      sleep 10; #Wait for cloudflare to do it's thing
}

哒哒哒!

我花了很长时间才做到这一点。