首页 > 解决方案 > 如何使用 Beautiful soup 从该页面获取价格?

问题描述

我正在尝试从此页面获取价格(即 152 美元) 。我在 find_all 方法中尝试了不同的标签组合,但我得到的只是空列表。我究竟做错了什么?

u = 'https://www.dianeslingerie.com/product/serie-piana-short-sleeve-tunic-by-mey/'
r = requests.get(url)
c = r.content
soup = BeautifulSoup(c, "html.parser")
soup.find_all('div', {'class':'summary-container'})

标签: pythonweb-scrapingbeautifulsoup

解决方案


这应该做你想要的:

import requests
from bs4 import BeautifulSoup

url = 'https://www.dianeslingerie.com/product/serie-piana-short-sleeve-tunic-by-mey/'

r = requests.get(url)

soup = BeautifulSoup(r.text, "html.parser")

price = soup.find('span', {'class': 'woocommerce-Price-amount amount'})

print(price.text)

为此,您可能需要检查页面并查找您要抓取的对象所独有的类、id 或 html 标记。

在这种情况下,“woocommerce-Price-amount amount”类仅出现在页面的价格中:显示 html 标记的页面截图

正如我们所看到的,它在一个 span 标签内,所以我们将它与我们之前找到的类一起使用,我们得到以下输出:

$152.00

推荐阅读