【问题标题】:Hpricot, Get all text from documentHpricot,从文档中获取所有文本
【发布时间】:2009-08-07 09:27:25
【问题描述】:

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

我基本上只想抓取文本,所以我最终得到了这样的字符串:

“这是我要抓取的,我也想抓取这段文字”

最好的方法是什么?

干杯

伊夫

【问题讨论】:

    标签: html ruby hpricot


    【解决方案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")
    

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

    【讨论】:

    • @Eef,您可能需要在收集文本数组(doc/"script").each {|js| js.inner_html=''}之前删除javascript代码。
    【解决方案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
    

    【讨论】:

      【解决方案3】:

      @weppos:这样会好一点:

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

      【讨论】:

      • 是的,但这假设他只想要 p 和 div。我想他什么都想要。
      猜你喜欢
      • 2013-07-06
      • 1970-01-01
      • 2020-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多