2012-07-05 51 views
0

我有一些HTML这样的:如何在Nokogiri中使用内联链接目标转储文本节点?

<span class="foo">foo bar <a href="http://example.com">example</a> baz</span> 

,我想将它变成像一个字符串:

foo bar http://example.com baz 

我使用引入nokogiri和我有一样的东西:

doc.css('.foo').each do |message| 
    message.css('a').map {|link| link.replace(link['href'])} 
    message.xpath('.//text()').map do |m| 
    p m.text 
    end 
end 

,但似乎放出来:

foo bar 
http://example.com 
baz 

我做错了什么?

+0

尝试用'puts(message.xpath('.// text()')。map {| m | m.text})。join“”'代替。 作为对风格的一般评论,您在错误的上下文中使用'map'。 'Map'将一个块应用于一个枚举的所有元素,并返回这些修改后的项目。在这种情况下,你正在使用'map',你应该使用'each'。 – 2012-07-05 15:12:45

+0

看起来好像会起作用,我最终将内部循环外部的变量添加到内部,然后再打印出来。 – Stuart 2012-07-05 16:46:12

回答

1

p m.text将在每行文本后面插入换行符,但文档本身没有任何换行符。只需打印message.text,你应该得到你想要的。

require 'rubygems' 
require 'nokogiri' 

doc = Nokogiri::HTML.fragment(DATA.read) 
doc.css('.foo').each do |message| 
    message.css('a').each {|link| link.replace(link['href'])} 
    puts message.text # prints "foo bar http://example.com baz" 
end 

__END__ 
<span class="foo">foo bar <a href="http://example.com">example</a> baz</span> 
相关问题