4

我刚刚开始学习 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>

我基本上只想抓取文本,所以我最终得到一个字符串,如下所示:

“这就是我要抢的,我也想抢这个文字”

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

干杯

伊夫

4

3 回答 3

10

您可以使用 XPathtext()选择器执行此操作。

require 'hpricot'
require 'open-uri'

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

然而,这是一项相当昂贵的操作。可能会有更好的解决方案。

于 2009-08-07T09:41:53.873 回答
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
于 2011-10-31T18:45:04.830 回答
0

@weppos:这会更好一些:

text = doc/"//p|div/text()" # array of text values
于 2009-08-07T11:01:03.603 回答