Python与BeautifulSoup/Requests:请求返回字节串如何解码?
解决网页字节流解码问题
从你给出的reg_papers.content开头的\xff\xfe字节序列可以确定,这个常规论文页面采用的是UTF-16LE编码(\xff\xfe是UTF-16LE的字节顺序标记,即BOM),这就是你用UTF-8解码报错的核心原因。
下面是两种可行的解决方法:
方法1:手动解码字节内容
直接指定UTF-16LE编码对返回的字节流解码,再传入BeautifulSoup解析:
import requests from bs4 import BeautifulSoup reg_papers = requests.get('https://my_conference.org/regular.html') # 用UTF-16LE解码字节内容 decoded_html = reg_papers.content.decode('utf-16le') soup = BeautifulSoup(decoded_html, 'html.parser') # 后续和特邀论文页面相同的解析逻辑 datas = soup.find_all("td") for data in datas: cleaned_text = ' '.join(data.text.split()) print(cleaned_text)
方法2:设置requests的编码属性
手动给requests响应对象指定正确编码,之后直接用text属性获取解码后的文本:
import requests from bs4 import BeautifulSoup reg_papers = requests.get('https://my_conference.org/regular.html') # 强制设置编码为UTF-16LE reg_papers.encoding = 'utf-16le' soup = BeautifulSoup(reg_papers.text, 'html.parser') # 执行解析操作 datas = soup.find_all("td") for data in datas: cleaned_text = ' '.join(data.text.split()) print(cleaned_text)
额外说明
- 本地保存后能正常解析是因为编辑器会自动识别UTF-16LE的BOM并正确解码,但requests的默认编码猜测机制没识别到这个编码,导致
text属性解码错误。 - 你后续可以学习用BeautifulSoup的标签层级或CSS选择器精准定位目标区域,无需手动处理冗余内容。
内容的提问来源于stack exchange,提问作者Alasdair
相关产品推荐
相关产品推荐

