html - 如何在解析文档时告诉 Nokogiri 不要将其转换为不同的编码(在我的例子中不要将 &paund; 转换为其他任何东西)

标签 html encoding nokogiri

我如何告诉 Nokogiri 不要将文档转换为不同的编码,在我的例子中不要将 &paund; 转换为任何其他编码?

我有一个文件包含:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<span>&pound;</span>
</body>
</html>

我用 Nokogiri 解析它:

d = Nokogiri::HTML.parse(open('/tmp/in.html', 'r'))

如果我打印文档“d”,我得到:

<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n
<html>\n
<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"></head>\n
<body>\n
<span>\302\243</span>\n
</body>\n
</html>\n

注意:£变成了“\302\243”(或者用ISO-8859-1编码的£变成了UTF-8编码)

如果我将文档“d”保存到一个文件中:

open('/tmp/out.html', 'w') do |out|
out << d.to_html
end

我得到以下信息:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"></head>
<body>
<span>ВЈ</span>
</body>
</html>

&paund;解析文档,并将其保存到文件后,我得到了两个符号而不是“BJ”。

我想我没有在某个步骤指定编码,但我不确定在哪里。

最佳答案

文档中 Nokogiri 对“parse”的定义,查找编码:

# File lib/nokogiri/html.rb, line 22

22:       def parse thing, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT_HTML, &block
23:         Document.parse(thing, url, encoding, options, &block)
24:       end

关于html - 如何在解析文档时告诉 Nokogiri 不要将其转换为不同的编码(在我的例子中不要将 &paund; 转换为其他任何东西),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3288187/

相关文章:

ruby-on-rails - 尝试使用 RVM 安装 Rails 时如何修复错误

Ruby Mechanize、Nokogiri 和 Net::HTTP

ruby - xpath 挑战 : How to merge multiple results into one result

javascript - 创建用于显示视频的模态窗口

html - 使用伪类 :not and :before together

javascript - HTML 使用变量显示文本

javascript - 传单弹出窗口中图像的对齐

linux - 与 powershell 相比,Bash base64 有一个附加字符而不是 equals

c++ - 分析波头

c# - 将字符串写入文件会生成意外内容