Perl WWW::Mechanize Parse 内容问题?

标签 perl www-mechanize

我正在使用 Perl 中的 WWW::Mechanize 库从网站上抓取内容。然而,我注意到网页的原始 HTML 源代码和 WWW::Mechanize 解析的内容不同。因此,我的脚本中的某些功能被破坏。

所以,这是脚本(一个子集,只是为了演示错误/问题)

#! /usr/bin/perl

use WWW::Mechanize;
use warnings;

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

$url="http://www.example.com";

$mech->get($url);

print $mech->content;

代码简短,它将连接到网站并检索整个 HTML 页面。

我运行脚本并将输出重定向到文本文件,以便我可以分析它们。

perl test.pl >> source_code.txt

现在,当我比较 source_code.txt 和浏览器(Firefox)显示的网站的实际源代码时,发现存在差异。

例如:

<tr>
<td nowrap="nowrap">This is Some Text</td>
<td align="right"><a href="http://example.com?value=key">Some more Text</a></td>
</tr><tr>

以上源码是在浏览器中观察到的。 (查看页面源功能)

但是,在文本文件中,source_code.txt(由 WWW::Mechanize 生成)

它显示:

<tr>
<td nowrap="nowrap">This is some text</td>
<td align="right">This is some more text</td>
</tr><tr>

如您所见,嵌套在第二组标记之间的 anchor 标记已被删除。

这是一个已知问题还是我需要使用 $mech->content 之外的其他东西来查看源代码?

谢谢。

最佳答案

这是一种常见行为,称为 "user agent sniffing" ,例如对于盲人用户,页面将以不同的方式显示。您可以使用不同的插件在浏览器中更改用户代理字符串,也可以将其更改为@ LHMathies说,在 WWW::Mechanize 中参见 UserAgent.pmMechanize->new

示例:

my $mech = WWW::Mechanize->new( agent => 
     'Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)' 
);

另请参阅a list of common user agent strings

关于Perl WWW::Mechanize Parse 内容问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11964887/

相关文章:

ruby - cURL 有效但 Mechanize 无效

perl - [] 在这里是什么意思?

perl - -m 开关在 Perl 中如何工作

forms - perl WWW::Mechanize Submit_form() 直接写入文件?

perl - WWW::Scripter 的身份验证问题

perl - 如何使用 Perl 从网站下载链接目标?

perl - 需要更多有关如何使用 Spreadsheet::ParseExcel 的示例

regex - 正则表达式匹配后删除文本的有效方法

regex - Perl 正则表达式条件匹配

python - 使用 mechanize 和 Python 提交表单