Skip to main content
 首页 » 编程设计

Python,抓取 : bad utf8 characters writed in file from scraped html page with charset iso-8859-1

2025年05月04日28insus

我想在 python 2.7 中用 Scrapy 抓取一个带有字符集 iso-8859-1 的网页。我在网页上感兴趣的文字是:tempête

Scrapy 以 UTF8 unicode 格式返回响应,字符编码正确:

>>> response 
u'temp\xc3\xaate' 

现在,我想在文件中写入单词 tempête,所以我正在执行以下操作:

>>> import codecs 
>>> file = codecs.open('test', 'a', encoding='utf-8') 
>>> file.write(response) #response is the above var 

当我打开文件时,生成的文本是 tempête。似乎 python 没有检测到正确的编码并且无法读取两个字节编码的 char,并认为它是两个单编码的 char。

我该如何处理这个简单的用例?

请您参考如下方法:

在你的例子中,response 是一个(解码的)Unicode 字符串,里面有 \xc3\xa,然后在 scrapy 编码检测级别出现了问题。

\xc3\xa 是编码为 UTF-8 的字符 ê,因此您应该只看到(编码的)非 Unicode/str< 的那些字符 字符串(在 Python 2 中)

Python 2.7 shell session :

>>> # what your input should look like 
>>> tempete = u'tempête' 
>>> tempete 
u'temp\xeate' 
 
>>> # UTF-8 encoded 
>>> tempete.encode('utf-8') 
'temp\xc3\xaate' 
>>> 
>>> # latin1 encoded 
>>> tempete.encode('iso-8859-1') 
'temp\xeate' 
>>>  
 
>>> # back to your sample 
>>> s = u'temp\xc3\xaate' 
>>> print s 
tempête 
>>> 
>>> # if you use a non-Unicode string with those characters... 
>>> s_raw = 'temp\xc3\xaate' 
>>> s_raw.decode('utf-8') 
u'temp\xeate' 
>>>  
>>> # ... decoding from UTF-8 works 
>>> print s_raw.decode('utf-8') 
tempête 
>>>  

Scrapy 将页面解释为 iso-8859-1 编码时出现问题。

您可以通过从 response.body 重建响应来强制编码:

>>> import scrapy.http 
>>> hr1 = scrapy.http.HtmlResponse(url='http://www.example', body='<html><body>temp\xc3\xaate</body></html>', encoding='latin1') 
>>> hr1.body_as_unicode() 
u'<html><body>temp\xc3\xaate</body></html>' 
>>> hr2 = scrapy.http.HtmlResponse(url='http://www.example', body='<html><body>temp\xc3\xaate</body></html>', encoding='utf-8') 
>>> hr2.body_as_unicode() 
u'<html><body>temp\xeate</body></html>' 
>>>  

构建一个新的响应

newresponse = response.replace(encoding='utf-8') 

并改为使用 newresponse