我目前正在练习使用“纽约时报”最佳卖家网站进行网络抓取。我想在列表中获得第一本书的标题,并找到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").text但是,它返回列表中每一本书的标题。我如何才能得到一个专门的书名,“疯狂的亚洲富人”?
发布于 2018-09-07 20:35:12
如果您查看来自doc.css(".title")的返回,您将看到它是所有标题的集合。作为Nokogiri::XML::Element对象
据我所知,CSS没有针对给定类的第一个元素的选择器。(如果我错了,肯定有人会纠正我),但是从Nokogiri::XML::NodeSet获得第一个元素仍然非常简单,因为在许多情况下,它的作用就像Array。例如:
doc.css(".title")[0].text您还可以使用xpath来选择第一个(因为XPath支持基于索引的选择),如下所示:
doc.xpath(doc.xpath("(//h3[@class='title'])[1]").text请注意:
https://stackoverflow.com/questions/52228919
复制相似问题