2011-03-14 14 views
1

我試圖從給定的URL下載一些xml文件。下面是我所使用的各項─wget在Perl程序內不能正常工作

use strict; 
use warnings; 

my $url ='https://givenurl.com/'; 
my $username ='scott'; 
my $password='tiger'; 

system("wget --user=$username --password=$password $url") == 0 or die "system execution failed ($?): $!"; 
local $/ = undef; 
open(FILE, "<index.html") or die "not able to open $!"; 
my $index = <FILE>; 
my @childs = map /<a\s+href\=\"(AAA.*\.xml)\">/g , $index; 

for my $xml (@childs) 
{ 
    system("wget --user=$username --password=$password $url/$xml"); 
} 

但是當我運行此,它被卡在for循環wget命令的代碼。看來wget無法正確獲取文件?任何線索或建議?

謝謝。

+2

另請參閱:http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – 2011-03-14 11:58:46

+2

您是否嘗試用'print'替換'system' '?它是否卡在第一個「系統」上? 「系統」返回什麼? – Tim 2011-03-14 13:29:34

+0

獲取多個文件後它會卡住..有時它會在最後一個文件中獲取兩個文件.. – Man 2011-03-14 13:38:23

回答

0

也許是因爲路徑wget的,但如果你用的什麼:

system("/usr/bin/wget --user=$username --password=$password $url") 

或者我猜它可以與傳遞給system變量的一個問題:($username$password$url

+0

它適用於多個文件,但不適用於其他文件。此外,當我多次執行腳本時,它會被隨機卡住.. :( – Man 2011-03-14 14:20:13

+0

嘗試通過'print'更改'system'並查看輸出...也許'$ url'格式不正確,如果是這種情況那麼你可以使用'URL'模塊來構建'$ url' ...祝你好運 – Juan 2011-03-14 17:04:37

3

您不應該首先使用外部命令。 確保WWW::Mechanize是可用的,然後使用類似的代碼:

use strict; 
use warnings; 

use WWW::Mechanize; 

my $mech = WWW::Mechanize->new(); 

... 

$mech->credentials($username, $password); 
$mech->get($url); 
foreach my $link ($mech->find_all_links(url_regex=>qr/\bAAA/)) { 
    $mech->get($link); 
    ... 
} 
+0

非常感謝你,我發現它工作的很好.. – Man 2011-03-15 07:08:33

1

如果$url$xml包含任何shell元字符(?&是在URL中常見的),那麼你可能需要或者引用他們正確

system("wget --user=$username --password=$password '$url/$xml'"); 
system qq(wget --user=$username --password=$password "$url/$xml"); 

,或者使用LIST形式的system繞過外殼

system('wget', "--user=$username", "--password=$password", "$url/$xml"); 

以使命令正常工作。