我试图恢复一个简单的例子,在nokogiri的帮助下解析一个站点,并找到一个错误未定义的方法`children'为nil:NilClass(NoMethodError)
require 'open-uri'
url = 'http://www.cubecinema.com/programme'
html = open(url)
puts html
require 'nokogiri'
doc = Nokogiri::HTML(html)
showings = doc.css('.showing').map do |showing|
showing_id = showing['id'].split('_').last.to_i
tags = showing.css('.tags a')
.map{|tag| tag.text.strip}
title_el = showing.at_css('h1 a')
.children
.delete_if{|c| c.name == 'span'}
title = title_el.text.strip
dates = showing.at_css('.start_and_pricing')
.inner_html
.strip
.split('<br>')
.map(&:strip)
.map{|d| DateTime.parse(d)}
description = showing.at_css('.copy')
.text
.delete('[more...]')
.strip
{id: showing_id,
title: title,
tags: tags,
dates: dates,
description: description}
end
我找到了一个可能的解决方案https://translate.googleusercontent.com/translate_c?anno=2&depth=1&rurl=translate.google.com&sl=auto&sp=nmt4&tl=ru&u=https://github.com/dwightjack/grunt-email-boilerplate/issues/12&xid=25657,15700023,15700186,15700191,15700248,15700253&usg=ALkJrhgLkK2xqf-6SfL3K16DBRdtdNH0Cw,但不清楚预制器子任务是什么,阅读该网站并没有真正帮助他们,我在哪里需要写下这些子任务。我将非常感谢通过我的错误或者如何确定这些子任务的方式进行澄清,我自己也不理解并且缺乏经验。
由于缺乏声誉,我无法留下评论,因此我只能在答案部分给出建议。
所以,我认为你应该首先检查shows.at_css('h1 a')实例,以确保它有一个子方法。一些Nokogiri对象没有任何子节点(例如元标记)。希望能帮助到你。
我在本地运行你的程序,我在你正在抓取的代码部分找不到任何标签。
你得到这个错误的原因是因为Nokogiri返回一个nil元素并且你试图删除已经没有值的东西因此给你NilClass错误。
这是您尝试从中检索“h1 a”的代码部分。
<div class="showing" id="event_10427"> <div class="event_image"> <a href="/programme/event/vula-viel-do-not-be-afraid-album-tour,10427/">
<img src="/media/diary/thumbnails/MSJ_vvlive.jpg.600x0_q45.jpg" alt="Picture for event Vula Viel - “Do Not Be Afraid” Album Tour"></a> <span class="tags"> <a href="/programme/view/music/" class="tag_music">music</a> </span> </div> <!-- div event_image --> <a href="/programme/event/vula-viel-do-not-be-afraid-album-tour,10427/">
<p><span class="pre_title"> Ear Trumpet Music presents </span></p> <h3>Vula Viel - “Do Not Be Afraid” Album Tour</h3> <span class="post_title"> </span> </a> <p></p>
<div class="event_details"> <p class="start_and_pricing"> Thu 28 March // 20:00 <br> </p> <p class="copy">The trio of music makers called Vula Viel weave sparse polyrhythms and intricate rhythm structures around ... [<a class="more" href="/programme/event/vula-viel-do-not-be-afraid-album-tour,10427/">more</a>]</p> </div> </div>
正如您所看到的,没有h1标签,因此Nokogiri在您的搜索中返回nil。
如果代表您的错误,您可以更改标签;或者如果不是每个页面都有'h1 a'标签。您需要检查是否
title_el = showing.at_css('h3 a')
在尝试删除它之前返回nil。