2011-11-21 45 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 –