用Nokogiri解析

编程入门 行业动态 更新时间:2024-10-27 12:41:53
Nokogiri解析 - 不能迭代行(Parsing with Nokogiri - can't iterate over rows)

由于某种原因,此代码无效:

url = "http://www.ontariocourts.ca/decisions_index/2015.htm" doc = Nokogiri::HTML(open(url)) doc.css("table.judtbl tr").each do |i| title = i.at_css(".title p").content citation = i.at_css(".citation p").content p title p citation end

我一直在努力想弄清楚原因。 请帮帮我一个人!! 为什么不能遍历行?

For some reason this code is not working:

url = "http://www.ontariocourts.ca/decisions_index/2015.htm" doc = Nokogiri::HTML(open(url)) doc.css("table.judtbl tr").each do |i| title = i.at_css(".title p").content citation = i.at_css(".citation p").content p title p citation end

I have been going nuts trying to figure out why. Please help me someone!! Why can't this iterate over rows?

最满意答案

有时内部CSS选择器没有匹配,所以at_css(...)返回nil,这可能导致.content失败。 试试这个:

doc.css("table.judtbl tr").each do |tr| title = tr.at_css(".title p") citation = tr.at_css(".citation p") next unless title && citation # Skip the row if it has no title/citation. puts "OK: #{title.text} -- #{citation.text}" end

Sometimes the inner CSS selectors have no match so at_css(...) returns nil which probably causes .content to fail ungracefully. Try this instead:

doc.css("table.judtbl tr").each do |tr| title = tr.at_css(".title p") citation = tr.at_css(".citation p") next unless title && citation # Skip the row if it has no title/citation. puts "OK: #{title.text} -- #{citation.text}" end

更多推荐

本文发布于:2023-08-07 20:45:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465665.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Nokogiri

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!