我正在尝试使用 Beautiful Soup 从HTML中的某些类中提取文本。我已经成功获取了文本,但是其中有些异常(无法识别的字符),如下图所示。如何使用python代码解决问题,而不是手动删除这些异常。
码:
try:
html =requests.get(url)
except:
print("no conection")
try:
soup = BS(html.text,'html.parser')
except:
print("pasre error")
print(soup.find('div',{'class':'_3WlLe clearfix'}).get_text())
问题来源:stackoverflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
当您访问html.text时,请求会尝试确定字符编码,以便它可以正确解码从服务器接收到的原始字节。timesofindia发送的content-type
头是text / html; charset = iso-8859-1
,这是Requests附带的内容。字符编码几乎可以肯定是utf-8。
您可以通过在访问html.text之前将html的encoding设置为utf-8来解决此问题:
try:
html =requests.get(url)
html.encoding = 'utf-8'
except:
print("no conection")
try:
soup = BS(html.text,'html.parser')
except:
print("pasre error")
print(soup.find('div',{'class':'_3WlLe clearfix'}).get_text())
或将html.content解码为utf-8,然后将其传递到BS而不是html.text:
try:
html =requests.get(url)
except:
print("no conection")
try:
soup = BS(html.content.decode('utf-8'),'html.parser')
except:
print("pasre error")
print(soup.find('div',{'class':'_3WlLe clearfix'}).get_text())
我强烈建议您学习字符编码和Unicode。很容易被它绊倒。我们都去过那里。
字符,符号和Unicode奇迹-Tom Scott和Sean Riley撰写的Computerphile
David C. Zentgraf绝对需要每个程序员真正了解与文本一起使用的编码和字符集
每个软件开发人员绝对,肯定必须绝对了解Unicode和字符集(无借口!)作者:Joel Spolsky
回答来源:stackoverflow