我目前正在使用NYT Best Sellers网站练习网页抓取。我想在列表中获得#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").text
但是,它会返回列表中每本书的标题。我将如何获得具体的书名“疯狂的亚洲人”?
如果你看一下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
请注意: