我正在尝试从网站导入源代码,但问题是尝试导入的字符之一是î
并且导致错误。
这是我的代码:
import urllib.request
htmlfile = urllib.request.urlopen("url...")
htmltext=htmlfile.read()
print(htmltext)
这是错误:
Traceback (most recent call last):
File "/Users/****/Documents/Scraping.py", line 3, in <module>
htmlfile = urllib.request.urlopen("http://*****")
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 223, in urlopen
return opener.open(url, data, timeout)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 526, in open
response = self._open(req, data)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 544, in _open
'_open', req)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 504, in _call_chain
result = func(*args)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 1346, in http_open
return self.do_open(http.client.HTTPConnection, req)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 1318, in do_open
encode_chunked=req.has_header('Transfer-encoding'))
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1239, in request
self._send_request(method, url, body, headers, encode_chunked)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1250, in _send_request
self.putrequest(method, url, **skips)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1117, in putrequest
self._output(request.encode('ascii'))
UnicodeEncodeError: 'ascii' codec can't encode character '\xee' in position 32: ordinal not in range(128)
这也发生了:
"http://...url...".encode('ascii')
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
"http://www....url...".encode('ascii')
UnicodeEncodeError: 'ascii' codec can't encode character '\xee' in position 50: ordinal not in range(128)
答案 0 :(得分:0)
您是否尝试将解码添加到urlopen?添加(...).urlopen(URL).decode('utf-8')