2014-01-30 33 views
1

我想使用內置搜索功能中的網站從中收集數據,但無法解決如何按下「搜索」按鈕,因爲它有一些JavaScript纏繞它和id隨着頁面的每次新迭代而改變。perl使用HTML :: Treebuilder查找不同的元素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 something\n"; } 
    else { print "nothing found\n"; } 

    foreach my $node (@nodes) 
    { 
     print "node is $node\n"; 
     my $id = $node->findvalue('button'); 
     print "my id is $id\n"; 
    } 

可悲的是我的代碼不會返回任何節點的值。

非常感謝提前。

回答

1

這似乎工作:

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'); 
} 
+0

謝謝你,夥計,這似乎對這個HTML數據很好地工作,但不是當我嘗試它的網站本身。 (注意,我爲這篇文章收集了很多這方面的數據)在運行之前,我應該對url數據做些什麼? – MicrobicTiger

+0

以及如何將'id'分配給一個變量,以便稍後將其作爲按鈕單擊時調用它? – MicrobicTiger

+0

發佈未改變的html。你可能會發現這樣更容易用於你的目的:https://pypi.python.org/pypi/selenium – user353255

0

也許你可以嘗試一個更簡單的XPath查詢。你不需要在那裏有整個層次結構,這太過分了。很難得到正確的結果:您的HTML不包括您在查詢中的tbody(也不包括您還有的tbosy; - )。

試試這個,如果您發現該元素的方法是通過按鈕類和標題:

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