可以尝试以下两种方法
使用lxml解析器:Beautifulsoup包含多种解析器,其中lxml解析器速度较快,且能自动判断解析器类型。可以使用以下代码进行实现:
from bs4 import BeautifulSoup import requests
r = requests.get(url) soup = BeautifulSoup(r.content, "lxml")
缩小搜索范围:在Beautifulsoup中搜索时,可以限定搜索的标签,缩小搜索范围,从而减少解析时间。例如,如果我们只需要解析html中的所有p标签,可以这样实现:
from bs4 import BeautifulSoup import requests
r = requests.get(url) soup = BeautifulSoup(r.content, "html.parser") p_tags = soup.find_all("p")