【发布时间】:2013-02-25 19:56:03
【问题描述】:
我只是在用 ruby 中用 nokogiri 解析网站时遇到了一点问题。
这是网站的样子
<div id="post_message_111112" class="postcontent">
Hee is text 1
here is another
</div>
<div id="post_message_111111" class="postcontent">
Here is text 2
</div>
这是我的解析代码
doc = Nokogiri::HTML(open(myNewLink))
myPost = doc.xpath("//div[@class='postcontent']/text()").to_a()
ii=0
while ii!=myPost.length
puts "#{ii} #{myPost[ii].to_s().strip}"
ii+=1
end
我的问题是当它显示它时,由于Hee is text 1 之后的新行,to_a 让它变得很奇怪
myPost[0] = hee is text 1
myPost[1] = here is another
myPost[2] = here is text 2
我希望每个 div 都有自己的信息。喜欢
myPost[0] = hee is text 1 here is another
myPost[1] = here is text 2
如何解决这个谢谢
更新
我试过了
myPost = doc.xpath("//div[@class='postcontent']/text()").to_a()
myPost.each_with_index do |post, index|
puts "#{index} #{post.to_s().gsub(/\n/, ' ').strip}"
end
我放 post.to_s().gsub 是因为它抱怨 gsub 不是一种发布方法。但我仍然有同样的问题。我知道我做错了只是毁了我的头
更新 2
忘了说新行是<br />,甚至还有
doc.search('br').each do |n|
n.replace('')
end
或
doc.search('br').remove
问题依然存在
【问题讨论】:
标签: html ruby arrays parsing nokogiri