在创建BeautifulSoup对象时,指定正确的编码方式。如果无法确定编码方式,可以先尝试使用“utf-8”进行解码,如果仍然存在乱码,则可以尝试使用“ISO-8859-1”或“GBK”等编码方式进行解码。
示例代码:
import requests
from bs4 import BeautifulSoup
# 请求页面
url = "https://example.com/"
response = requests.get(url)
# 指定编码方式解码页面内容
response.encoding = "utf-8"
# 创建BeautifulSoup对象
soup = BeautifulSoup(response.text, 'html.parser')
# 查找元素
element = soup.select_one("#some_element")
print(element.text)