使用XPath的全部功能通常意味着您不必停止和迭代,只需用一个表达式直接获取所需内容。这允许您将表达式外部化、存储在变量中或以其他方式组织并更容易地维护它们,即使XML发生了变化。使用XPath,您甚至可以在表达式中包含一些逻辑。
target=rating
属性,因此您可以将其设置为关键点,而不是计数
span
doc.xpath('//*[@id="profile_top"]/span/a[@target="rating"]/text()')
#=> "Fiction M"
我建议的另一件事是使用HTTParty或Mechanize,如果你还没有。他们有不同的优势。HTTParty提供了一种简单的方法来创建一个具有抓取和解析功能的优秀的面向对象客户机。Mechanize专注于抓取,但它内置了Nokogiri,您可以访问底层的Nokogiri文档,然后开始在其上执行XPath。
在下面的评论中添加一些其他内容。
language = doc.xpath('//*[@id="profile_top"]/span[a[@target="rating"]]/text()').to_s.split(' - ')[1]
#=> "English"
注意,括号
[]
其中包含
与评级目标的链接。这样就不需要计算跨度,因为跨度更脆。
genres = doc.xpath('//*[@id="profile_top"]/span[a[@target="rating"]]/text()').to_s.split(' - ')[2].split('/')
#=> ["Humor", "Adventure"]
id = doc.xpath('//*[@id="profile_top"]/span[a[@target="rating"]]/text()').to_s.split(' - ')[5].split(': ')
#=> "12596791"
published = DateTime.strptime(doc.xpath('//*[@id="profile_top"]//span/@data-xutime').first.value, '%s')
#=> 2017-08-01T20:03:19+00:00
等等。我建议把XPath放在类似散列的东西中,这样你可以参考更具描述性的
xpath_for[:rating]