如何使用Perl访问Google Scholar

问题描述:

我使用下面的代码尝试从我的网站搜索Google Scholar,它将工作一次或两次,然后出现错误“Error GETing http://scholar.google.com:无法连接到学者.google.com:80(权限被拒绝)” - 我使用的代码如下:如何使用Perl访问Google Scholar

use strict; 
use WWW::Mechanize; 
my $browser = WWW::Mechanize->new(); 
$browser->get('http://scholar.google.com'); 
$browser->form_name('f'); 
$browser->field('q','PCR'); 
$browser->submit(); 
print $browser->content(); 

任何提示或建议非常赞赏

+2

你需要使用'的https:// scholar.google.com'? – mob 2015-02-10 20:39:23

+0

http://scholar.google.com将我重定向到https网址。 – Sobrique 2015-02-10 21:14:14

+0

是的,它是正确的URL,正如我所提到的,它有时作为http而不是https安全地工作 – neemie 2015-02-10 21:16:17

你的代码是不错,但谷歌学术决定不允许像LWP那样的“机器人”访问,请参阅perlmonks/461130了解更多信息。

编辑:我发现通过将用户代理和一个cookie ID在头一个解决方案:

use HTTP::Request; 
use HTTP::Cookies; 
use LWP::UserAgent; 

# randomize cookie id 
use Digest::MD5 qw(md5_hex); 
my $googleid = md5_hex(rand()); 

# escape query string 
use URI::Escape; 
my $query= uri_escape('search string'); 

# create request 
my $request = HTTP::Request->new(GET => 'http://scholar.google.com/scholar?q='.$query); 

# disguise as Mozilla 
my $ua = LWP::UserAgent->new; 
$ua->agent('Mozilla/5.0'); 

# use random id for Cookie 
my $cookies = HTTP::Cookies->new(); 
$cookies->set_cookie(0,'GSP', 'ID='.$googleid,'/','scholar.google.com'); 
$ua->cookie_jar($cookies); 

# submit request 
$response = $ua->request($request); 
if($response->is_success){ 
    print $response->code; 
    my $text = $response->decoded_content; 
    # do something 
}