【问题标题】:Perl WWW::Mechanize and cookiesPerl WWW::Mechanize 和 cookies
【发布时间】:2014-01-03 13:48:13
【问题描述】:

在使用 WWW::Mechanize 时遇到了一些问题。

我尝试加载的页面包含 Javascript,它会等待 30 秒,然后解析我需要单击的按钮(以确认我已同意网站条款:)

我知道 Mechanize 不适用于 JS,所以我需要使用 cookie 获取此页面,当我按下此按钮时,此站点会将其放入我的浏览器中。

这些 cookie 是这样的:agree=>1, lastvisit=>1388753990, lastseen=>0

我怎样才能获得带有这些 cookie 的所需页面?

代码:

my $cookie_jar = HTTP::Cookies->new;
my $agent      = WWW::Mechanize->new( cookie_jar => $cookie_jar );

$cookie_jar->set_cookie("agreed"=>1,"lastseen"=>0,"lastvisit"=>1388753990);

$agent->get( 'http://www.example.com' );

print $agent->content();

感谢您的帮助!

【问题讨论】:

  • 您可以使用LWPx::ParanoidAgent进行简单查询并设置cookie_jar,您可以通过手动设置cookie找到解决方法,但是如果您需要执行JS可以使用JavaScript::SpiderMonkey

标签: perl cookies mechanize


【解决方案1】:

如果你想要真正的机械化,请移至WWW-Mechanize-Firefox 然后你就得到了真正的工作 JS 环境:

use WWW::Mechanize::Firefox;
my $mech = WWW::Mechanize::Firefox->new();
$mech->get('http://ursite.com');

# The submit button is generated after the page has loaded

my $retries = 10;
while ($retries-- and ! $mech->is_visible( xpath => '//*[@id="submit"]' )) {
      sleep 1;
};
die "Timeout" if 0 > $retries;

# Now the element exists
$mech->click({xpath => '//*[@id="submit"]'});

【讨论】:

  • 完美! Спасибо:) 但是我在没有显卡的服务器上安装 WWW::Mechanize::Firefox 时遇到了一个小问题:) 有没有办法从 shell 安装这个模块,而不启动 Firefox 并启动 MozRepl?
猜你喜欢
  • 1970-01-01
  • 2011-12-14
  • 1970-01-01
  • 1970-01-01
  • 2011-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多