UnicodeDecodeError错误urllib.reques

2024-03-29 07:30:46 发布

您现在位置:Python中文网/ 问答频道 /正文

当我在Python3中使用urllib获取网页的HTML代码时,我使用以下代码:

def getHTML(url):
    request = Request(url)
    request.add_header('User-Agent', 'Mozilla/5.0')
    html = urlopen(request).read().decode('utf-8')
    print(html)
    return html

但是,每次都会失败,并出现以下错误:

^{pr2}$

page是UTF-8格式的,我正在根据urllib文档正确地解码它。据我所知,该页不是gzip或其他字符集。在

url.info().get_charset()返回页的None,但是meta标记指定UTF-8。我在任何程序中查看HTML没有问题。在

我不想使用任何外部库。在

有解决办法吗?怎么回事?使用以下Python2代码可以很好地工作:

def getHTML(url):
    opener = urllib2.build_opener()
    opener.addheaders = [('User-Agent', 'Mozilla/5.0')]
    response = opener.open(url)
    html = response.read()
    return html

Tags: 代码urlmozillareadreturnrequestdefhtml
2条回答

在那里,发现了你的错误,分析工作做得很好,一切都评估得很好。但仔细阅读回溯:

Traceback (most recent call last): File 
"/Users/chris/Documents/Code/Python/HLTV Parser/getTeams.py", line 56, in <module> 
 getHTML('hltv.org/team/7900/spirit-academy') File 
"/Users/chris/Documents/Code/Python/HLTV Parser/getTeams.py", line 53, in getHTML 
 print(html) 
UnicodeEncodeError: 'ascii' codec can't encode characters in position 10636-10638: ordinal not in range(128) 
[Finished in 1.14s]

错误是由print语句引起的,如您所见,这在回溯print(html)中。在


这是一个常见的例外,它只是告诉您,使用当前的系统编码,有些文本无法打印到控制台。一个简单的解决方案是添加print(html.encode('ascii', 'ignore'))来忽略所有不可打印的字符。你仍然可以用html做其他的事情,只是你不能打印它。在

如果您想要更好的“修复”:https://wiki.python.org/moin/PrintFails

顺便说一句:re模块可以搜索字节字符串。照原样复制,将有效:

^{pr2}$

你不需要decode('utf-8')

获取的html应该返回以下html。在

def getHTML(url):
    request = Request(url)
    request.add_header('User-Agent', 'Mozilla/5.0')
    html = urlopen(request).read()
    return html

相关问题 更多 >