【问题标题】:bs4 can't recognize encoding python3bs4无法识别编码python3
【发布时间】: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?

标签: python-3.x beautifulsoup


【解决方案1】:

您可以按如下方式更改编码。这应该可以解决您的错误。

r = requests.get("https://s3.amazonaws.com/codecademy-content/courses/beautifulsoup/cacao/index.html")
print(r.encoding)

soup = BS(r.content, 'html.parser').encode('utf-8')

print(soup)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-21
    • 1970-01-01
    • 1970-01-01
    • 2020-05-17
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    相关资源
    最近更新 更多