Skip to main content
 首页 » 编程设计

python之Python 3 的 UTF-8 编码问题

2024年10月17日7EasonJim

<分区>

我写了a Wikipedia scraper上周在 Python 中学习。

它会抓取法语页面,因此我必须管理 UTF-8 编码以避免错误。我在脚本的开头用这些行来做到这一点:

#!/usr/bin/python 
# -*- coding: utf-8 -*- 

我也像这样对抓取的字符串进行编码:

adresse = monuments[1].get_text().encode('utf-8') 

我的第一个脚本在 Python 2.7 上运行得非常好,但我为 Python 3 重写了它(尤其是使用 urllib.request)并且 UTF-8 不再工作。

抓取前几个元素后我得到了这些错误:

File "scraper_monu_historiques_ge_py3.py", line 19, in <module> 
    url = urllib.request.urlopen(url_ville).read() # et on ouvre chacune d'entre elles 
File "/usr/lib/python3.4/urllib/request.py", line 153, in urlopen 
    return opener.open(url, data, timeout) 
File "/usr/lib/python3.4/urllib/request.py", line 455, in open 
    response = self._open(req, data) 
File "/usr/lib/python3.4/urllib/request.py", line 473, in _open 
'_open', req) 
File "/usr/lib/python3.4/urllib/request.py", line 433, in _call_chain 
    result = func(*args) 
File "/usr/lib/python3.4/urllib/request.py", line 1217, in https_open 
    context=self._context, check_hostname=self._check_hostname) 
File "/usr/lib/python3.4/urllib/request.py", line 1174, in do_open 
h.request(req.get_method(), req.selector, req.data, headers) 
File "/usr/lib/python3.4/http/client.py", line 1090, in request 
self._send_request(method, url, body, headers) 
File "/usr/lib/python3.4/http/client.py", line 1118, in _send_request 
self.putrequest(method, url, **skips) 
File "/usr/lib/python3.4/http/client.py", line 975, in putrequest 
self._output(request.encode('ascii')) 
UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 58: ordinal not in range(128) 

我不明白为什么,因为它在 Python 2.7 中运行良好...我发布了 a version of this WIP on Github .