Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/88.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
下载没有Python unicode错误的html_Python_Html_Xml_Unicode_Character Encoding - Fatal编程技术网

下载没有Python unicode错误的html

下载没有Python unicode错误的html,python,html,xml,unicode,character-encoding,Python,Html,Xml,Unicode,Character Encoding,我正在尝试将page_源文件下载到一个文件中。然而,每次我得到一个: 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进行“预处理”以将其转换为“可写”格式 我不

我正在尝试将page_源文件下载到一个文件中。然而,每次我得到一个:

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进行“预处理”以将其转换为“可写”格式

我不确定,但是它有一个函数。prettify返回格式良好的HTML。您可以尝试使用它进行预处理。

问题可能是您正在尝试使用str->utf-8,而您需要使用str->unicode->utf-8。换句话说,试试unicodes“utf-8”。编码“utf-8”


有关更多信息,请参阅。

有第三方库,如和,可以自动处理编码问题。但这里有一个仅使用URLLIB2的粗略示例:

首先下载一些包含非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'

文件的实际编码是什么?谢谢,这解决了我的问题。下载带有基本python脚本的页面时,我得到了一个带有xce\xbf\xb9等的html页面。
>>> text = data.decode('utf-8')