Perl使用HTML :: TreeBuilder查找不同的元素ID



我正在尝试使用构建搜索功能中的网站收集数据,但无法弄清楚如何按'搜索'按钮,因为它围绕它包裹了一些JavaScript,并且ID随页面的每个新迭代而变化。

网站部分的数据如下。

<html>
 <head>
 </head>
 <body>
  <table>
   <tr>
    <td>
    <td>
     <table>
      <tr>
       <td>
        <!-- start of toolbar Main -->
        <table>
         <tr>
          <td>
           <table>
            <tr class="buttonPad">
            </tr>
            <tr>
   *          <td nowrap="true" valign="top" class="button"><a id="S7674" accesskey="S" class="button" title="SEARCH" onclick="dispatch('S7674');"><u>S</u>></td>
            </tr>
           </table>
          </td>
          <td</td>
         </tr>
        </table>
      </td>
      </tr>
     </table>
    </td>
    </td>
   </tr>
  </table>
 </body>
</html>

和我的代码

   my $tree= HTML::TreeBuilder::XPath->new;
      $tree->parse($url);
   my @nodes = $tree->findnodes('/html/body/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr/td/table.buttonSpace/tbosy/tr/a.button')->get_nodelist; # line is modified later.
   my $nodecount = scalar(@nodes);
   if ($nodecount > 0 ) { print "we found somethingn"; }
   else { print "nothing foundn"; } 
   foreach my $node (@nodes)
   {
      print "node is $noden";
      my $id = $node->findvalue('button');
      print "my id is $idn";
   }

可悲的是,我的代码不会返回任何节点值。

非常感谢。

micro

这似乎有效:

use strict;
use warnings;
use HTML::TreeBuilder;
use Data::Dumper;
my $html = <<HTML;
<html>
 <head>
 </head>
 <body>
  <table>
   <tr>
    <td>
    <td>
     <table>
      <tr>
       <td>
        <!-- start of toolbar Main -->
        <table>
         <tr>
          <td>
           <table>
            <tr class="buttonPad">
            </tr>
            <tr>
            <td nowrap="true" valign="top" class="button"><a id="S7674" accesskey="S" class="button" title="SEARCH" onclick="dispatch('S7674');"><u>S</u>></td>
            </tr>
           </table>
          </td>
          <td</td>
         </tr>
        </table>
      </td>
      </tr>
     </table>
    </td>
    </td>
   </tr>
  </table>
 </body>
</html>
HTML
my $tree = HTML::TreeBuilder->new_from_content( $html );
foreach my $atag ( $tree->look_down( _tag => q{a}, 'class' => 'button', 'title' => 'SEARCH' ) ) {
    print Dumper $atag->attr('id');
}

您可能可以尝试更简单的XPath查询。您不需要在那里拥有整个层次结构,这是过分的。很难正确:您的HTML不包括您在查询中所拥有的tbody(也不包括您也拥有的tbosy; - )。

如果您通过按钮类和标题识别元素的方式:

$tree->findnodes( '//td[@class="button"]/a[@class="button" and @title="SEARCH"]')

最新更新