2011-03-21 58 views
7

的XPath的获取内容我有这样红宝石引入nokogiri节点

@doc = Nokogiri::HTML(open(url) 
@doc.xpath(query).each do |html| 

    puts html # how get content of a node 
end 

代码和我的问题是如何得到该节点的内容,因为现在我得做这样的。

<li class="stat"> 

回答

11

这是README file用于引入nokogiri的概要例子示出了使用CSS,XPath或混合做到这一点的一种方法:

require 'nokogiri' 
require 'open-uri' 

# Get a Nokogiri::HTML:Document for the page we’re interested in... 

doc = Nokogiri::HTML(open('http://www.google.com/search?q=tenderlove')) 

# Do funky things with it using Nokogiri::XML::Node methods... 

#### 
# Search for nodes by css 
doc.css('h3.r a.l').each do |link| 
    puts link.content 
end 

#### 
# Search for nodes by xpath 
doc.xpath('//h3/a[@class="l"]').each do |link| 
    puts link.content 
end 

#### 
# Or mix and match. 
doc.search('h3.r a.l', '//h3/a[@class="l"]').each do |link| 
    puts link.content 
end 
5

html.contenthtml.text

参见Node documentation

+1

链接已经死了,也许你想指向:http://www.rubydoc.info/gems/nokogiri/Nokogiri/XML/Node吧? – 2017-01-19 13:55:03