我有以下代码:
use WWW::Mechanize;
$url = "http://daccess-ods.un.org/access.nsf/Get?Open&DS=A/HRC/WGAD/2015/28&Lang=E";
$mech = WWW::Mechanize->new();
$mech->get($url);
$content = $mech->content();
while ($content =~ m/<META HTTP-EQUIV="refresh" CONTENT="(\d+); URL=(.+?)">/) {
$refresh = $1;
$link = $2;
sleep $refresh;
$mech->get($link);
$content = $mech->content();
}
$mech->save_content("output.txt");
当我将分配给 $url
的 URL 放在浏览器中时,最终结果是下载了一个 PDF
文件,但是当我运行上面的代码时,我最终用不同的文件。我认为 Mechanize
可能无法正确处理 cookie。我怎样才能让它发挥作用?
最佳答案
当你请求http://daccess-ods.un.org/access.nsf/Get?Open&DS=A/HRC/WGAD/2015/28&Lang=E您首先会重定向到 https
。
然后您将获得一个带有 META REFRESH
的页面。这会在 /TMP
中为您提供一个文件。
得到https://daccess-ods.un.org/TMP/xxx.xxx.html后并按照 META REFRESH
到 https://documents-dds-ny.un.org/doc/UNDOC/GEN/G15/263/87/PDF/G1526387.pdf?OpenElement它仍然没有下载文档,但给出了错误消息。
从浏览器检查标题的原因是浏览器设置了三个 cookie,而 WWW::Mechanize 只设置了一个:
- citrix_ns_id=xxx
- citrix_ns_id_.un.org_%2F_wat=xxx
- LtpaToken=xxx
那么这些 cookie 是从哪里来的呢?事实证明,TMP html 不仅仅是一个 META REFRESH。它还有这个 HTML:
<frameset ROWS="0,100%" framespacing="0" FrameBorder="0" Border="0">
<frame name="footer" scrolling="no" noresize target="main" src="https://documents-dds-ny.un.org/prod/ods_mother.nsf?Login&Username=freeods2&Password=1234" marginwidth="0" marginheight="0">
<frame name="main" src="" scrolling="auto" target="_top">
<noframes>
<body>
<p>This page uses frames, but your browser doesn't support them.</p>
</body>
</noframes>
</frameset>
此网址 https://documents-dds-ny.un.org/prod/ods_mother.nsf?Login&Username=freeods2&Password=1234确实设置了这些 cookie。
Set-Cookie: LtpaToken=xxx; domain=.un.org; path=/
Set-Cookie: citrix_ns_id=xxx; Domain=.un.org; Path=/; HttpOnly
Set-Cookie: citrix_ns_id_.un.org_%2F_wat=xxx; Domain=.un.org; Path=/
因此,通过更改您的代码以考虑到这一点:
use strict;
use WWW::Mechanize;
my $url = "http://daccess-ods.un.org/access.nsf/Get?Open&DS=A/HRC/WGAD/2015/28&Lang=E";
my $mech = WWW::Mechanize->new();
$mech->get($url);
my $more = 1;
while ($more) {
$more = 0;
my $follow_link;
my @links = $mech->links;
foreach my $link (@links) {
if ($link->tag eq 'meta') {
$follow_link = $link;
}
if (($link->tag eq 'frame') && ($link->url)) {
$mech->follow_link( url => $link->url );
$mech->back;
}
}
if ($follow_link) {
$more = 1;
$mech->follow_link( url => $follow_link->url );
}
}
$mech->save_content("output.txt");
output.txt 成功包含 pdf。
$ file output.txt
output.txt: PDF document, version 1.5
关于html - Mechanize 不像浏览器那样处理 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35935911/