2011-03-21 61 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