Html 使用Nokogiri更改内容类型不会';行不通
我想更改“http equiv”内容类型标记中的字符集。因为我在代码的其他部分使用Nokogiri,所以我也希望在这个处理步骤中使用它 以下是示例代码:Html 使用Nokogiri更改内容类型不会';行不通,html,ruby,nokogiri,Html,Ruby,Nokogiri,我想更改“http equiv”内容类型标记中的字符集。因为我在代码的其他部分使用Nokogiri,所以我也希望在这个处理步骤中使用它 以下是示例代码: http_equiv = doc.at('meta[@http-equiv]') if !http_equiv.nil? && !http_equiv["http-equiv"].nil? && http_equiv["http-equiv"].downcase.eql?("content-type")
http_equiv = doc.at('meta[@http-equiv]')
if !http_equiv.nil? && !http_equiv["http-equiv"].nil? && http_equiv["http-equiv"].downcase.eql?("content-type")
http_equiv["content"] = "text/html; charset=utf-8"
end
content = doc.to_html.encode(Encoding::UTF_8)
问题是输入内容总是与输出内容相同。Nokogiri什么也没做
基于一个答案,我创建了一个真实世界的示例,与生成的示例相比,它不起作用
require 'nokogiri'
require 'open-uri'
doc = require 'open-uri'
doc = Nokogiri::HTML(open("http://www.spiegel.de/politik/deutschland/hooligans-gegen-salafisten-demo-in-koeln-eskaliert-a-999401.html"))
content_type = doc.at('meta[@http-equiv="Content-Type"]')
content_type['content'] = 'text/html; charset=UTF-8'
puts doc.to_html
我会这样做:
require 'nokogiri'
doc = Nokogiri::HTML(<<EOT)
<html>
<head>
<meta http-equiv="content-type" content="text/html">
</head>
<body>
foo
</body>
</html>
EOT
content_type = doc.at('meta[@http-equiv="content-type"]')
content_type['content'] = 'text/html; charset=UTF-8'
puts doc.to_html
将告诉Nokogiri输出HTML,尝试从ISO-8859-1转换为UTF-8。但是,由于存在一些不兼容,因此无法保证正确发生
您最初的尝试使用:
content = doc.to_html.encode(Encoding::UTF_8)
无法正常工作,因为HTML编码发生在特殊字符上。您必须在对字符进行HTML编码之前更改字符编码,如果使用
对HTML(编码:“UTF-8”)
请给出您正在解析的HTML的最小示例。doc=require'open-air'
?那是什么?看看我的问题-我把你的答案用在了一个真实世界的网站上。它不会更改内容类型。它会更改内容类型。它不会改变文档的编码,这是另一个问题。如果您希望发生这种情况,请参阅附加的答案。
content_type['content'] << '; charset=UTF-8'
doc.to_html(encoding: 'UTF-8')
content = doc.to_html.encode(Encoding::UTF_8)