我试图抓取一个网站,但它给了我一个错误。

我正在使用以下代码:

import urllib.request
from bs4 import BeautifulSoup

get = urllib.request.urlopen("https://www.website.com/")
html = get.read()

soup = BeautifulSoup(html)

print(soup)

我得到以下错误:

File "C:\Python34\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 70924-70950: character maps to <undefined>

我该怎么补救呢?


当前回答

在保存get请求的响应时,在窗口10的Python 3.7上抛出了相同的错误。从URL接收到的响应,编码是UTF-8,所以总是建议检查编码,这样就可以传递相同的编码,以避免这种琐碎的问题,因为它真的在生产中浪费了大量的时间

import requests
resp = requests.get('https://en.wikipedia.org/wiki/NIFTY_50')
print(resp.encoding)
with open ('NiftyList.txt', 'w') as f:
    f.write(resp.text)

当我用open命令添加encoding="utf-8"时,它会以正确的响应保存文件

with open ('NiftyList.txt', 'w', encoding="utf-8") as f:
    f.write(resp.text)

其他回答

在保存get请求的响应时,在窗口10的Python 3.7上抛出了相同的错误。从URL接收到的响应,编码是UTF-8,所以总是建议检查编码,这样就可以传递相同的编码,以避免这种琐碎的问题,因为它真的在生产中浪费了大量的时间

import requests
resp = requests.get('https://en.wikipedia.org/wiki/NIFTY_50')
print(resp.encoding)
with open ('NiftyList.txt', 'w') as f:
    f.write(resp.text)

当我用open命令添加encoding="utf-8"时,它会以正确的响应保存文件

with open ('NiftyList.txt', 'w', encoding="utf-8") as f:
    f.write(resp.text)

如果您使用的是Windows,请尝试传递encoding='latin1', encoding='iso-8859-1'或encoding='cp1252' 例子:

csv_data = pd.read_csv(csvpath,encoding='iso-8859-1')
print(print(soup.encode('iso-8859-1')))

我通过添加.encode("utf-8")来解决这个问题。

这意味着print(soup)变成print(soup.encode("utf-8"))。

对于那些仍然得到这个错误的人,添加encode(“utf-8”)到soup也可以解决这个问题。

soup = BeautifulSoup(html_doc, 'html.parser').encode("utf-8")
print(soup)

从Python 3.7开始, 将环境变量PYTHONUTF8设置为1

下面的脚本还包括其他有用的变量,用于设置系统环境变量。

setx /m PYTHONUTF8 1
setx PATHEXT "%PATHEXT%;.PY" ; In CMD, Python file can be executed without extesnion.
setx /m PY_PYTHON 3.10 ; To set default python version for py