问题可能出在Beautifulsoup无法稳定捕捉到页面的所有价格列表,某些列表可能需要进行不同的解析器处理。下面是一个使用lxml解析器的示例代码:
import requests
from bs4 import BeautifulSoup
response = requests.get("https://example.com")
soup = BeautifulSoup(response.content, 'lxml')
# 在这里找到页面上所有的价格元素
prices = soup.find_all("div", {"class": "price"})
# 如果prices不为空则打印元素列表
if len(prices) > 0:
for price in prices:
print(price.text.strip())
else:
print("没有找到价格。")
在这里,我们用find_all
方法查找页面上所有满足给定类名的元素。我们使用lxml
解析器来解析页面内容。如果页面中存在价格元素,则将所有访问到的价格元素打印出来。否则,它会返回“没有找到价格。”