【问题标题】:Ruby HTML scraper written in Hpricot having trouble with escaped HTML用 Hpricot 编写的 Ruby HTML 刮板遇到转义 HTML 的问题
【发布时间】:2011-02-17 11:59:55
【问题描述】:

我正在尝试抓取此页面:http://www.udel.edu/dining/menus/russell.html。我使用 Hpricot 库在 Ruby 中编写了一个刮板。

问题:HTML 页面被转义,我需要显示它未转义

example: "M&M" should be "M&M"  
example: "Entrée" should be "Vegetarian Entrée"  

我曾尝试在 Ruby 中使用 CGI 库(不太成功)和通过this Stack Overflow 帖子找到的 HTMLEntities gem。

HTMLEntities 在测试期间有效:

require 'rubygems' 
require 'htmlentities'
require 'cgi'

h = HTMLEntities.new
puts "h.decode('Entrée') = #{h.decode("Entrée")}"

blank = " "
puts "h.decode blank = #{h.decode blank}"
puts "CGI.unescapeHTML blank = |#{CGI.unescapeHTML blank}|"

puts "h.decode '<th width=86 height=59 scope=row>Vegetarian Entr&eacute;e</th> ' = |#{h.decode '<th width=86 height=59 scope=row>Vegetarian Entr&eacute;e</th> '}|"  

正确产生

h.decode('Entr&eacute;e') = Entrée
h.decode blank =  
CGI.unescapeHTML blank = |&nbsp;|
h.decode '<th width=86 height=59 scope=row>Vegetarian Entr&eacute;e</th> ' = |<th width=86 height=59 scope=row>Vegetarian Entrée</th> |

但是,当我在带有 open-uri 的文件上使用它时,它无法正常工作:

require 'rubygems'
require 'hpricot'
require 'open-uri'
require 'htmlentities'
require 'cgi'
f = open("http://www.udel.edu/dining/menus/russell.html")
htmlentity = HTMLEntities.new
while line = f.gets
  puts htmlentity.decode line
end

错误地产生如下内容:

<th width="60" height="59" scope="row">Vegetarian Entrée</th>

<th scope="row"> </th>  // note: was originally '&nbsp;' to indicate a blank

但通过让步正确处理 M&M:

<td valign="middle" class="menulineA">M&M Brownies</td>

我是否错误地处理了转义的 HTML?我不明白为什么它在某些情况下有效,而在其他情况下无效。

我正在运行 ruby​​ 1.8.7 (2009-06-12 patchlevel 174) [i486-linux]

感谢任何帮助/建议。谢谢。

【问题讨论】:

    标签: ruby html-parsing escaping open-uri html-entities


    【解决方案1】:

    HTMLEntities 似乎可以工作,但您遇到了编码问题。您正在打印的终端可能已针对脚本输出的 utf-8 字符设置了拉丁字符集和 barfs。

    你在什么环境下运行 ruby​​ ?

    '&' 正确显示的原因是它是一个 ascii 字符,因此在大多数编码中都将显示相同的字符。问题是它不应该单独出现在 xml 文档中,并且在您输入解码后可能会出现问题文件到 hpricot。我相信正确的方法是使用 hpricot 进行解析,然后将您从文档中提取的内容传递给 HTMLEntity。

    【讨论】:

    • 您对编码问题的看法完全正确。我终于意识到,当我在 xemacs 中打开文件时会出现问题,但是当我只是对文件执行“更多”命令并在终端中打印时,问题并没有出现。我猜 xemacs 只是没有设置为读取 UTF8 文件,因为当我切换到 gedit 进行踢球时,问题也没有出现。谢谢!
    • 我不使用 xemacs,但我认为合理的最新版本会了解 utf-8。对于 emacs 中的信息,我将使用的命令将称为 revert-buffer-with-coding-system 键盘快捷键 'ctrl+x r utf-8'
    猜你喜欢
    • 2014-06-02
    • 2011-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-12
    • 2014-05-28
    • 2019-05-02
    • 1970-01-01
    相关资源
    最近更新 更多