【发布时间】:2018-09-11 15:23:35
【问题描述】:
我第一次尝试使用 Python3 抓取几页。我已经多次使用 Python2 和 bs4 没有任何问题,但我似乎无法切换到 python3,因为我总是遇到编码错误。
例如,我正在尝试抓取https://www.pgatour.com/webcom/tournaments/the-bahamas-great-exuma-classic/leaderboard.html
我在这里搜索了几个有类似问题的线程,但没有成功。
这是我的代码:
r = requests.get('https://www.pgatour.com/webcom/tournaments/the-bahamas-great-exuma-classic/leaderboard.html')
r.encoding = r.apparent_encoding
soup = bs.BeautifulSoup(r.text,'html5lib')
print(soup)
我收到以下错误:
UnicodeEncodeError: 'ascii' codec can't encode character '\xd7' in position 28935: ordinal not in range(128)
我也尝试将r.encoding = r.apparent_encoding 更改为r.encoding = "utf-8",得到同样的错误。
【问题讨论】:
-
您的代码对我有用。也可以在不设置编码的情况下工作。检查 r.encoding 是否为 'utf-8'
-
改编码前为ISO-8859-1,改后为utf-8
-
你能在不改变编码的情况下解析和打印汤吗?
-
不,如果我删除 r.encoding 行,我会得到同样的错误。
-
你是否为python3重新安装了html5lib?