如何在 Nokogiri 中使用 XPath? [英] How do I use XPath in Nokogiri?
问题描述
我还没有找到任何相关的文档或教程.有这样的东西吗?
I have not found any documentation nor tutorial for that. Does anything like that exist?
doc.xpath('//table/tbody[@id="threadbits_forum_251"]/tr')
上面的代码可以让我得到任何table
,只要有一个tbody
子元素,属性id
等于threadbits_forum_251".但是为什么它以双 //
开头?为什么最后有/tr
?有关详细信息,请参阅Ruby Nokogiri 解析 HTML 表 II".
The code above will get me any table
, anywhere, that has a tbody
child with the attribute id
equal to "threadbits_forum_251". But why does it start with double //
? Why there is /tr
at the end? See "Ruby Nokogiri Parsing HTML table II" for more details.
谁能告诉我如何提取href
、id
、alt
、src
等,使用诺克切里?
Can anybody tell me how to extract href
, id
, alt
, src
, etc., using Nokogiri?
td[3]/div[1]/a/text()' <--- extracts text
如何提取其他内容?
推荐答案
看来你需要阅读XPath 教程
您的//table/tbody[@id="threadbits_forum_251"]/tr
表达式表示:
//
- XML 文档中的任何位置table/tbody
- 获取一个带有 tbody 子元素的 table 元素[@id="threadbits_forum_251"]
- 其中 id 属性等于threadbits_forum_251"tr
- 并取其tr
元素
//
- Anywhere in your XML documenttable/tbody
- take a table element with a tbody child[@id="threadbits_forum_251"]
- where id attribute are equals to "threadbits_forum_251"tr
- and take itstr
elements
所以,基本上,你需要知道:
So, basically, you need to know:
- 属性以
@
开头 - 条件放在
[]
括号内
如果我正确理解该 API,您可以使用 doc.xpath("td[3]/div[1]/a")["href"]
或 td[3]/div[1]/a/@href
如果只有一个 元素.
If I correcly understood that API, you can go with doc.xpath("td[3]/div[1]/a")["href"]
, or td[3]/div[1]/a/@href
if there is just one <a>
element.
这篇关于如何在 Nokogiri 中使用 XPath?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!