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