我正在尝试使用 WWW::Mechanize::Firefox 抓取内部站点上的所有链接。该网站通过 javascript 加载一些内容,因此我必须首先单击同一类“展开”的某些元素。网站的结构是这样的:
<table>
<tr>
<td>
<a id="xyz" href="somesite"> Content </a>
</td>
</tr>
<tr>
<td>
<div>
<a id="twistie" onclick="expand_this">
<img class="expand" border="0" width="13" height="13" alt="Show All" title="Show All" src="images/plus.gif">
</a>
</div>
</td>
</tr>
</table>
单击图像会在 div 容器中加载更多内容。在网站上,有多个此类扩展图像,我必须单击所有图像才能访问所有内容。这就是我失败的地方。
到目前为止我已经尝试过:
$mech->click( { xpath => '//img[@class="expand"]', synchronize => 0 } );
这仅单击第一个图像元素。
my @images = $mech->xpath( '//img[@class="expand"]', synchronize => 0 );
返回我可以在页面上手动计算的尽可能多的数组元素。但是,我对如何将返回的数组元素插入到点击操作中有点迷失。
我可以使用打开第一个元素
$mech->click( { xpath => '//img[@class="expand"][0]', synchronize => 0 } );
但是
$mech->click( { xpath => '//img[@class="expand"][1]', synchronize => 0 } );
返回我
No elements found for //img[@class="expand"][1] at (eval 1377)[/usr/share/perl/5.18/perl5db.pl:732] line 2.
我进一步尝试了这种方法:
foreach my $id ( 0 .. scalar @images ) {
print $id, "\n";
$mech->click( { xpath => qq(//img[\@class="expand"]["$id"]), synchronize => 0 });
}
但这不会打开任何元素(不知道为什么)。
我在这里遗漏了什么吗?由于图像不幸缺少 ID,我需要做什么才能单击共享类的所有 img 标签?
最佳答案
您已经拥有包含图像对象的 Perl 数组 - 只需迭代它,而不是要求 mech 迭代其集合。
foreach (@images) { $mech->click($_) }
关于javascript - WWW::Mechanize::Firefox 单击某个类的所有图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35776474/