我在使用 ruby 中的 nokogiri 对网站进行 parising 时遇到了一个小问题。
这是网站的样子
<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 不是 post 的方法。但我仍然有同样的问题。我知道我做错了只是伤了我的头
更新 2
忘了说新行是<br />
甚至还有
doc.search('br').each do |n|
n.replace('')
end
或
doc.search('br').remove
问题依旧
最佳答案
如果您查看 myPost
array,你会看到每个 div 实际上都是它自己的消息。第一个恰好包含换行符 \n
.要用空格替换它,请使用 #gsub(/\n/, ' ')
.所以你的循环看起来像这样:
myPost.each_with_index do |post, index|
puts "#{index} #{post.to_s.gsub(/\n/, ' ').strip}"
end
编辑:
据我有限的了解,xpath只能找节点。子节点是<br />
, 所以要么你在它们之间有多个文本,要么你有 div
标签包含在您的搜索中。确实有一种方法可以在 <br />
之间加入文本节点,但我不知道。
在您找到它之前,这里有一些有用的东西:
将您的 xpath 匹配替换为
"//div[@class='postcontent']"
调整循环以删除 div 标签:
myPost.each_with_index do |post, index| post = post.to_s post.gsub!(/\n/, ' ') post.gsub!(/^<div[^>]*>/, '') # delete opening div tag post.gsub!(%r|</\s*div[^>]*>|, '') # delete closing div tag puts "#{index} #{post.strip}" end
关于html - ruby 解析问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15325050/