2011-11-21 41 views
3

我無法專門找到此問題,希望我沒有錯,因爲它是對舊問題的新變體。使用Ruby/Mechanize在選定元素後選擇下一個元素

我希望能夠在(不一致)p.red元素text()後選擇表格,其中'p'不包含文字「按字母順序排列」但包含文字「OVERALL」。 。

的DOM看起來是這樣的:

<p class=red>Some Text</p> 
    <table class="newclass"> 
    <tr></tr> 
    <tr></tr> 
</table> 

<p class=red>Some Text</p> 
<table class="newclass"> 
    <tr></tr> 
    <tr></tr> 
</table> 

<p class=red>OVERALL</p> 
<table class="newclass"> 
    <tr></tr> 
    <tr></tr> 
</table> 
  • 表在每一頁不同支數的用武之地。

我想得到那個p標籤的文本(),但也得到它後面的表。同樣,在文本()包含「整體」但不是「字形」的地方..我應該建立一個數組和.reject()的元素沒有匹配?我現在還不確定,而且對於使用Ruby和Mechanize,我還相當陌生,在此先感謝您的幫助!

回答

0

使用引入nokogiri的CSS評價是非常乾淨的:

require 'nokogiri' 

doc = Nokogiri::HTML(<<EOT) 
<p class=red>Some Text</p> 
    <table class="newclass"> 
    <tr></tr> 
    <tr></tr> 
</table> 

<p class=red>Some Text</p> 
<table class="newclass"> 
    <tr></tr> 
    <tr></tr> 
</table> 

<p class=red>OVERALL</p> 
<table class="newclass"> 
    <tr></tr> 
    <tr></tr> 
</table> 
EOT 

puts doc.at('p:contains("OVERALL")').to_html 
# >> <p class="red">OVERALL</p> 

puts doc.at('p:contains("OVERALL") ~ table').to_html 
# >> <table class="newclass"> 
# >> <tr></tr> 
# >> <tr></tr> 
# >> </table> 
1

p標籤:

agent.parser.xpath('//p[.="OVERALL"]')[0] 

表:

agent.parser.xpath('//p[.="OVERALL"]')[0].next.next 

或:

agent.parser.xpath('//p[.="OVERALL"]/following-sibling::table[1]')[0] 
+0

只是希望能夠在Mechanise對象中找到下一個標記的提示。 parser.xpath,當你的代理被創建爲'agent = Mechanize.new'時。您需要添加 –

+0

無意中提交了以前的評論,5分鐘後無法更改。只是希望能夠在Mechanise對象中找到下一個標籤的人提示。 'parser'是一個Nokogiri方法,因此在調用'class'時必須確保你的對象是'Nokogiri :: XML :: Element'。如果代理的創建類似'agent = Mechanize.new',那麼agent.parser.xpath將不起作用(至少在Mechanise 2.7.3中),並且將爲main:Object返回一個錯誤「NameError:undefined local variable或method'parser' '。 'agent.page.parser.path'不過會起作用。 –

+0

鏈接到與以前的評論相關的有用的帖子http://stackoverflow.com/questions/23064821/using-the-mechanize-gem-with-the-nokogirl-gem?rq=1 –