Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Html 在Ruby中使用Nokogiri抓取特定标题_Html_Ruby_Web Scraping_Nokogiri_Screen Scraping - Fatal编程技术网

Html 在Ruby中使用Nokogiri抓取特定标题

Html 在Ruby中使用Nokogiri抓取特定标题,html,ruby,web-scraping,nokogiri,screen-scraping,Html,Ruby,Web Scraping,Nokogiri,Screen Scraping,我目前正在使用纽约时报的畅销书网站练习网络抓取。我想获取列表中1本书的标题,并找到HTML元素: <div class="book-body"> <p class="freshness">12 weeks on the list</p> <h3 class="title" itemprop="name">CRAZY RICH ASIANS</h3> <p class="author" itemprop="author"

我目前正在使用纽约时报的畅销书网站练习网络抓取。我想获取列表中1本书的标题,并找到HTML元素:

<div class="book-body">
  <p class="freshness">12 weeks on the list</p>
  <h3 class="title" itemprop="name">CRAZY RICH ASIANS</h3>
  <p class="author" itemprop="author">by Kevin Kwan</p>
  <p itemprop="description" class="description">A New Yorker gets a surprise when she spends the summer with her boyfriend in Singapore.</p>
</div>

但是,它返回列表中每本书的标题。我怎样才能得到一本书的书名,疯狂的亚洲人

如果您查看doc.css.title的返回,您将看到它是所有标题的集合。作为Nokogiri::XML::Element对象

据我所知,CSS没有针对给定类的第一个元素的选择器。如果我错了,肯定会有人纠正我的错误,但是从Nokogiri::XML::NodeSet中只获取第一个元素仍然非常简单,因为它在许多情况下就像一个数组。例如:

doc.css(".title")[0].text
您还可以使用xpath仅选择第一个,因为xpath支持基于索引的选择,如下所示:

doc.xpath(doc.xpath("(//h3[@class='title'])[1]").text
请注意:

Ruby索引从0开始,如第一个示例所示; XPath索引从1开始,如第二个示例所示。
您可以选择类的第一个元素。标题:第一个-type@josephcho根据我的理解和基本测试,这不是选择器的工作方式。它是一个父子选择器,因此您将从每个div的书体中获得第一个type.title:first of type>。title可能会起作用,但我不知道页面的确切上下文,因此我不能保证这一点either@engineersmnky-doc.css.title[0]。文本就像一个符咒。像数组一样查看节点集确实有助于我更好地理解它。@Sharq很高兴它有帮助,在这种情况下,请随意将其标记为正确
doc.xpath(doc.xpath("(//h3[@class='title'])[1]").text