-->

角度来说,Hpricot,获取从文档中的所有文本(Hpricot, Get all text fro

2019-09-22 11:18发布

我刚开始学习Ruby。 非常酷的语言,喜欢它了很多。

我使用的是非常方便的角度来说,Hpricot HTML解析器。

我所希望做的是抓住所有网页中的文本,但不包括HTML标记。

例:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <title>Data Protection Checks</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <div>
        This is what I want to grab.
        </div>
        <p>
        I also want to grab this text
        </p>
    </body>
</html>

我基本上想这样我结束了像这样的字符串抢只有文字:

“这是我想要抓住什么。我也想抓住这个文本”

什么是这样做的最佳方法是什么?

干杯

EEF

Answer 1:

为此,您可以使用XPath text()选择。

require 'hpricot'
require 'open-uri'

doc  = open("http://stackoverflow.com/") { |f| Hpricot(f) }
text = (doc/"//*/text()") # array of text values
puts text.join("\n")

然而,这是一个公平的昂贵的操作。 一个更好的解决方案可能是可用的。



Answer 2:

你可能会想尝试inner_text。

像这样:

h = Hpricot("<html><body><a href='http://yoursite.com?utm=trackmeplease'>http://yoursite.com</a> is <strong>awesome</strong>")
puts h.inner_text
http://yoursite.com is awesome


Answer 3:

@weppos:这将是好一点。

text = doc/"//p|div/text()" # array of text values


文章来源: Hpricot, Get all text from document