gpt4 book ai didi

ruby - 您如何使用 Nokogiri 遍历 HTML 文档、搜索并跳到下一个项目?

转载 作者:太空宇宙 更新时间:2023-11-03 16:28:12 24 4
gpt4 key购买 nike

如何遍历到找到的某个元素,然后继续找到下一个元素?在我的示例中,我尝试搜索第一个元素,获取文本,然后继续搜索,直到找到下一个标签或找到特定标签。我还需要考虑标签的原因是因为我想在那里做一些事情。

HTML

<table border=0>
<tr>
<td width=180>
<font size=+1><b>apple</b></font>
</td>
<td>Description of an apple</td>
</tr>
<tr>
<td width=180>
<font size=+1><b>banana</b></font>
</td>
<td>Description of a banana</td>
</tr>
<tr>
<td><img vspace=4 hspace=0 src="common/dot_clear.gif"></td>
</tr>
...Then this repeats itself in a similar format

当前scrape.rb

#...
document.at_css("body").traverse do |node|
#if <font> is found
#puts text in font
#else if <img> is found then
#puts img src and continue loop until end of document
end

谢谢!

最佳答案

很有趣。您基本上想要遍历树中的所有 children 并根据获得的节点执行一些操作。

所以我们可以这样做:

#Acquiring dummy page
page = Nokogiri::HTML(open('http://en.wikipedia.org/wiki/Ruby_%28programming_language%29'))

现在,如果您想开始遍历所有 body 元素,我们可以使用 XPath 来拯救我们。 XPath 表达式://body//* 将返回 body 中的所有 childrengrand-children

这将返回类为 Nokogiri::XML::Element 的元素数组

page.xpath('//body//*')
page.xpath('//body//*').first.node_name
#=> "div"

因此,您现在可以遍历该数组并执行您的操作:

page.xpath('//body//*').each do |node|
case node.name
when 'div' then #do this
when 'font' then #do that
end
end

关于ruby - 您如何使用 Nokogiri 遍历 HTML 文档、搜索并跳到下一个项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20766854/

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