[英]Beautiful Soup HTML parsing anamoly
当您访问html.text
,Requests 会尝试确定字符编码,以便正确解码从服务器接收到的原始字节。 timesofindia 发送的content-type
头是text/html; charset=iso-8859-1
text/html; charset=iso-8859-1
,这是 Requests 所用的。 字符编码几乎肯定是utf-8
。
您可以通过在访问html.text
之前将html
的encoding
设置为utf-8
来解决此html.text
:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.