【发布时间】:2014-08-14 20:36:20
【问题描述】:
我需要使用 Nokogiri 和 CSS 或 XPath 选择器来匹配来自以下 HTML 的文本。它应该从<div> 标记开始匹配,其中class="propsBar" 并在<div> 标记的结束侧结束匹配,其中class="oddsInfoBottom"。应该这样做以识别与此模式的所有匹配项:
<div class="timeBar"></div>
<div class="propsBar"></div>
<div class="oddsInfoTop"></div>
<div class="oddsInfoBottom"></div>
<!--
BUY POINTS
-->
<input id="events[X2036-907-Yes-No-081414]" type="hidden" value="X2036-907-Yes-No-081414^No^Yes^Nationals (S Strasburg) @ Met…l there be a score in the 1st Inning?^8/14/2014^7:10 PM^2036" name="events[X2036-907-Yes-No-081414]"></input>
<div class="timeBar"></div>
<div class="propsBar"></div>
<div class="oddsInfoTop"></div>
<div class="oddsInfoBottom"></div>
<!--
BUY POINTS
-->
<input id="events[X2036-915-Yes-No-081414]" type="hidden" value="X2036-915-Yes-No-081414^No^Yes^Astros (S Feldman) @ Red Sox …l there be a score in the 1st Inning?^8/14/2014^7:10 PM^2036" name="events[X2036-915-Yes-No-081414]"></input>
<div class="timeBar"></div>
<div class="propsBar"></div>
<div class="oddsInfoTop"></div>
<div class="oddsInfoBottom"></div>
<!--
BUY POINTS
-->
<input id="events[X2036-917-Yes-No-081414]" type="hidden" value="X2036-917-Yes-No-081414^No^Yes^Rays (J Odorizzi) @ Rangers (…l there be a score in the 1st Inning?^8/14/2014^8:05 PM^2036" name="events[X2036-917-Yes-No-081414]"></input>
<div class="timeBar"></div>
上面的 HTML 应该返回三个匹配项。
到目前为止,我能够做到这一点的唯一方法是:
one = html.xpath("//div[@class='propsBar']")
two = html.xpath("//div[@class='oddsInfoTop']")
three = html.xpath("//div[@class='oddsInfoBottom']")
one.zip(two, three).flatten.each_slice(3).map(&:join)
这样做的缺点是只返回文本,不再作为 Nokogiri 元素。此外,我认为这样解析很危险,如果页面有不同数量的匹配one, two, three的元素,它将中断。
【问题讨论】:
-
您尝试过哪些 XPath 查询?
-
“要求很高”?期望您提供已尝试过的示例,因为它表明您不只是在寻找其他人为您编写的代码。我们修复您的代码也比我们编写代码和您将其硬塞到您编写的任何内容中更容易。如果您走错了路,它还可以帮助我们避免问题。 Stack Overflow 不仅是一个“解决我的问题”网站,还是一个“帮助我通过最佳实践学习和成长”的网站。 meta.stackoverflow.com/a/254575/128421 是一个很好的元答案,尤其是第 2 项。
标签: html css ruby xpath nokogiri