如何在Ruby 1.9.1中将Net :: HTTP响应转换为某种编码?

hum*_*nzz 9 ruby encoding http sinatra ruby-1.9

我有一个Sinatra应用程序(http://analyzethis.espace-technologies.com)执行以下操作

  1. 检索HTML页面(通过net/http)
  2. 从response.body创建Nokogiri文档
  3. 提取一些信息并将其发送回响应中.响应应该是UTF-8编码

所以我在尝试阅读使用windows-1256编码的网站时遇到了这个问题,例如www.filfan.com或www.masrawy.com.

问题是虽然没有抛出错误,但编码转换的结果不正确.

net/http response.body.encoding给出ASCII-8BIT,它不能转换为UTF-8

如果我做Nokogiri :: HTML(response.body)并使用css选择器从页面获取某些内容 - 例如标题标签的内容 - 我得到一个字符串,当我调用string.encoding返回WINDOWS-1256 .我使用string.encode("utf-8")并使用它发送响应,但同样响应不正确.

关于我的方法有什么问题的任何建议或想法?

A.D*_*.D. 22

因为Net :: HTTP无法正确处理编码.见http://bugs.ruby-lang.org/issues/2567

您可以解析response['content-type']包含charset而不是解析整体的内容response.body.

然后force_encoding()用来设置正确的编码.

response.body.force_encoding("UTF-8") 如果网站以UTF-8提供.


hum*_*nzz 3

我发现以下代码现在对我有用

def document
  if @document.nil? && response
    @document = if document_encoding
                  Nokogiri::HTML(response.body.force_encoding(document_encoding).encode('utf-8'),nil, 'utf-8')
                else
                  Nokogiri::HTML(response.body)
                end
  end
  @document
end

def document_encoding
  return @document_encoding if @document_encoding
  response.type_params.each_pair do |k,v|
    @document_encoding = v.upcase if k =~ /charset/i
  end
  unless @document_encoding
    #document.css("meta[http-equiv=Content-Type]").each do |n|
    #  attr = n.get_attribute("content")
    #  @document_encoding = attr.slice(/charset=[a-z1-9\-_]+/i).split("=")[1].upcase if attr
    #end
    @document_encoding = response.body =~ /<meta[^>]*HTTP-EQUIV=["']Content-Type["'][^>]*content=["'](.*)["']/i && $1 =~ /charset=(.+)/i && $1.upcase
  end
  @document_encoding
end 
Run Code Online (Sandbox Code Playgroud)