我试着用漂亮的汤从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())发布于 2020-03-13 09:44:47
访问html.text时,请求尝试确定字符编码,以便正确解码从服务器接收到的原始字节。timesofindia发送的content-type头是text/html; charset=iso-8859-1,这就是请求的内容。字符编码几乎肯定是utf-8。
您可以通过在访问encoding of html之前将html.text设置为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。很容易被它绊倒。我们都去过那里。
汤姆·斯科特( Tom )和肖恩·莱利( Sean ) 字符、符号和Unicode奇迹-计算机
大卫·辛格拉夫( David C. Zentgraf )著的“每个程序员绝对、积极地需要了解编码和字符集才能处理文本。”
https://stackoverflow.com/questions/60666528
复制相似问题