【问题标题】:Download html without Python unicode errors下载没有 Python unicode 错误的 html
【发布时间】:2012-02-05 16:45:34
【问题描述】:

我正在尝试将 page_source 下载到文件中。但是,每次我得到一个:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 (or something else) in 
position 8304: ordinal not in range(128)

我尝试过使用value.encode('utf-8'),但似乎每次它都会抛出相同的异常(除了手动尝试替换每个非ASCII字符)。有没有办法对 html 进行“预处理”以将其转换为“可写”格式?

【问题讨论】:

  • 文件的实际编码是什么?

标签: python html xml unicode character-encoding


【解决方案1】:

有诸如BeautifulSouplxml 等第三方库可以自动处理编码问题。但这是一个仅使用 urlllib2 的粗略示例:

首先下载一些包含非ASCII字符的网页:

>>> import urllib2
>>> response = urllib2.urlopen('http://www.ltg.ed.ac.uk/~richard/unicode-sample.html')
>>> data = response.read()

现在看看页面顶部的“字符集”:

>>> data[:200]
'<html>\n<head>\n<title>Unicode 2.0 test page</title>\n<meta
content="text/html; charset=UTF-8" http-equiv="Content-type"/>\n
</head>\n<body>\n<p>This page contains characters from each of the
Unicode\ncharact'

如果没有明显的字符集,“UTF-8”通常是一个很好的猜测,无论如何。

最后,将网页转换为 unicode 文本:

>>> text = data.decode('utf-8')

【讨论】:

  • 谢谢,这解决了我的问题。当下载一个带有基本 python 脚本的页面时,我得到了一个带有 xce\xbf\xb9 等的 html 页面。
【解决方案2】:

问题可能是你试图去str -> utf-8,当你需要去str -> unicode -> utf-8。换句话说,试试unicode(s, 'utf-8').encode('utf-8')

请参阅http://farmdev.com/talks/unicode/ 了解更多信息。

【讨论】:

    【解决方案3】:

    我不确定,但是 http://www.crummy.com/software/BeautifulSoup/ 有一个函数 .prettify() 可以返回格式良好的 HTML。您可以尝试将其用于“预处理”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-29
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-05
      相关资源
      最近更新 更多