You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Request和Beautiful Soup爬取数据出现乱码该如何解决

问题原因

这是典型的编码解码不匹配导致的乱码问题:站点返回的内容是UTF-8编码,字节流被错误用Latin-1(ISO-8859-1)规则解码后,就会出现单个特殊字符被拆分为多个乱码字符的情况,你代码里的错误点如下:

  • 手动给响应对象设置了encoding = 'utf-8-sig',但后续解析时用的是未经过编码转换的scrapTable.content原始字节流,前面设置的编码规则完全没有生效
  • 调用pd.read_html时传入的是已经转为Python字符串的str(table),此时再指定encoding='utf8'属于无效操作,反而可能引发二次编码错误
解决方法

两种修改方案都可以解决乱码问题,按需选择即可:

方案1:直接使用requests自动解码的文本内容

requests会自动根据响应头推断正确的编码,直接用.text属性获取解码后的字符串传入BeautifulSoup即可:

import pandas as pd
from requests import get
from bs4 import BeautifulSoup

scrapTable = get('https://widgets.sports-reference.com/wg.fcgi?css=1&site=bbr&url=%2Fleagues%2FNBA_2021_per_game.html&div=div_per_game_stats')
soup_a = BeautifulSoup(scrapTable.text, 'html.parser')
table = soup_a.find('table')
df_nba_PerGame = pd.read_html(str(table))[0]

方案2:给BeautifulSoup显式指定字节流编码

如果需要直接处理原始字节流,给BeautifulSoup补充from_encoding参数指定编码规则即可:

import pandas as pd
from requests import get
from bs4 import BeautifulSoup

scrapTable = get('https://widgets.sports-reference.com/wg.fcgi?css=1&site=bbr&url=%2Fleagues%2FNBA_2021_per_game.html&div=div_per_game_stats')
soup_a = BeautifulSoup(scrapTable.content, 'html.parser', from_encoding='utf-8')
table = soup_a.find('table')
df_nba_PerGame = pd.read_html(str(table))[0]

修改后运行即可正常识别Luka Dončić这类带特殊字符的球员姓名。

内容的提问来源于stack exchange,提问作者amayito37

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 15:48:03