2015-02-10 13 views
2

我使用下面的代碼嘗試從我的網站搜索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

回答

1

你的代碼是不錯,但谷歌學術決定不允許像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 
}