我正在用Ruby (1.9)编写一个爬虫,它会消耗来自许多随机站点的大量HTML。
当尝试提取链接时,我决定只使用.scan(/href="(.*?)"/i)
而不是nokogiri/hpricot (主要的加速)。问题是我现在收到了很多"invalid byte sequence in UTF-8
“错误。
据我所知,net/http
库没有任何特定的编码选项,而且传入的内容基本上没有正确标记。
实际处理这些传入数据的最佳方式是什么?我在设置了replace和invalid选项的情况下尝试了.encode
,但到目前为止还没有成功...
发布于 2012-01-16 06:30:33
在Ruby1.9.3中,可以使用String.encode“忽略”无效的UTF-8序列。下面是一个可以在1.8 (iconv)和1.9 (String#encode)中使用的代码片段:
require 'iconv' unless String.method_defined?(:encode)
if String.method_defined?(:encode)
file_contents.encode!('UTF-8', 'UTF-8', :invalid => :replace)
else
ic = Iconv.new('UTF-8', 'UTF-8//IGNORE')
file_contents = ic.iconv(file_contents)
end
或者,如果您有非常麻烦的输入,您可以执行从UTF-8到UTF-16再到UTF-8的双重转换:
require 'iconv' unless String.method_defined?(:encode)
if String.method_defined?(:encode)
file_contents.encode!('UTF-16', 'UTF-8', :invalid => :replace, :replace => '')
file_contents.encode!('UTF-8', 'UTF-16')
else
ic = Iconv.new('UTF-8', 'UTF-8//IGNORE')
file_contents = ic.iconv(file_contents)
end
发布于 2013-08-27 07:02:58
被接受的答案或其他答案对我都有效。我找到了this post,它建议
string.encode!('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '')
这为我解决了这个问题。
发布于 2012-01-14 04:44:54
我目前的解决方案是运行:
my_string.unpack("C*").pack("U*")
这至少会摆脱我的主要问题--异常
https://stackoverflow.com/questions/2982677
复制相似问题