【问题标题】:bytes to str conversion failure in python3python3中的字节到str转换失败
【发布时间】:2014-10-30 05:07:59
【问题描述】:

代码不言自明...

$ python3
Python 3.4.0 (default, Apr 11 2014, 13:05:18) 
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib.request as req
>>> url = 'http://bangladeshbrands.com/342560550782-44083.html'
>>> res = req.urlopen(url)
>>> html = res.read() 
>>> type(html)
<class 'bytes'>
>>> html = html.decode('utf-8') # bytes -> str
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x92 in position 66081: invalid start byte

【问题讨论】:

  • 你为什么不首先使用知道如何通过 HTTP 正确处理 HTML 的模块?
  • @IgnacioVazquez-Abrams,你能解释一下吗? read() 方法对大多数 url 都正常工作。
  • read() 方法不会为您提供有关服务器告诉您 HTML 字符集是什么的任何信息。
  • @IgnacioVazquez-Abrams,您能提出任何替代解决方案吗?

标签: python-3.x character-encoding


【解决方案1】:

您从 url 获得的信息中似乎有一些错误的 unicode 字符,因此需要进行某种错误处理。为什么不使用 requests,一个“用 Python 编写的用于人类的 HTTP 库”。并让它处理细节:

$ python3
Python 3.4.2 (default, Oct 15 2014, 22:01:37) 
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> url = 'http://bangladeshbrands.com/342560550782-44083.html'
>>> r = requests.get(url)
>>> html_as_text = r.text
>>> print(html_as_text[66070:66090])
ml">Toddler�s items<
>>> 

【讨论】:

    【解决方案2】:

    html 页面可能有inconsistent encodings。内容类型 HTTP 标头 (res.headers.get_content_charset()) 表示它是 'utf-8'。 html 文档中的&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; 确认了这一点。但是html.decode('utf-8') 失败了。

    看来问题出在智能引用 "’" (U + 2019 RIGHT SINGLE QUOTATION MARK) 上。它使用cp1252 编码b'\x92'(来自UnicodeDecodeError 消息的字节)进行编码。要修复它,您可以使用UnicodeDammit.detwingle():

    from bs4 import UnicodeDammit # $ pip install beautifulsoup4
    
    text = UnicodeDammit.detwingle(html).decode('utf-8')
    

    尽管对于这个特定的文档,html.decode('cp1252') 产生了相同的结果,也就是说,它可能只是 http 服务器和 html 创作工具的错误字符编码规范。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-27
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-17
      相关资源
      最近更新 更多