gpt4 book ai didi

ruby - 使用 Ruby/Mechanize 在选定元素之后选择下一个元素

转载 作者:数据小太阳 更新时间:2023-10-29 08:05:43 24 4
gpt4 key购买 nike

我无法具体找到这个问题,希望我没有错,它是一个旧问题的新变体。

我希望能够在(不一致的)p.red 元素 text() 之后选择表格,其中“p”不包含文本“Alphabetical”但确实包含文本“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 标签的 text(),但也想获得它后面的表格。同样,在 text() 包含“OVERALL”但不包含“ALPHABETICAL”的地方......我应该构建一个数组并 .reject() 没有匹配的元素吗?我现在不确定,我对使用 Ruby 和 Mechanize 还很陌生,在此先感谢您的帮助!

最佳答案

使用 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>

关于ruby - 使用 Ruby/Mechanize 在选定元素之后选择下一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8207044/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com