###源代码
import requests
from bs4 import BeautifulSoup
res = requests.get("https://www.autohome.com.cn/news/",)
soup=BeautifulSoup(res.text,'lxml')
ul=soup.find(class_="article")
print(ul)
乱码情况为:
ÈÕǰ£¬ÓйúÄÚýÌ屨µÀ³Æ£¬±ÈÑǵϹٷ½ÔÚ½ÓÊܲɷÃʱ±íʾ£¬Æä¼Æ»®µ½2025ÄêÔÚÈÕ±¾¿ªÉè100¼Òµç¶¯Æû³µÏúÊÛÃŵ꣬µ«Ä¿Ç°²¢Ã»ÓÐÔÚÈÕ±¾½¨³§.
解决方法:(将文本先拿出,进行重新编码,在放入bs4soup中)
res = requests.get("https://www.autohome.com.cn/news/",)
#'iso-8859-1为浏览器默认的字符编码
Html=res.text.encode('iso-8859-1').decode('gbk')#对编码格式为gbk方式读取
# 实例化soup对象
soup = BeautifulSoup(Html, 'lxml')