价格比较 - python

Price comparison - python

大家好,我正在尝试在 python 中创建一个程序来比较网站上的价格,但我无法获得价格。我已经使用下面的代码成功获取了产品的名称和数量。

page = requests.get(urls[7],headers=Headers)
soup = BeautifulSoup(page.text, 'html.parser')

title = soup.find("h1",{"class" : "Titlestyles__TitleStyles-sc-6rxg4t-0 fDKOTS"}).get_text().strip()
quantity = soup.find("li", class_="quantity").get_text().strip()
total_price = soup.find('div', class_='Pricestyles__ProductPriceStyles-sc-118x8ec-0 fzwZWj price')
print(title)
print(quantity)
print(total_price)

我正在尝试从该网站获取价格(我正在创建一个程序来寻找 diper 价格,哈哈)https://www.drogasil.com.br/fralda-huggies-tripla-protecao-tamanho-m.html

即使我收到的文本总是说它的非类型,价格也不会到来。

一些信息是通过 javascript 根据存储在 HTML 的 <script> 部分中的数据构建的。您可以通过搜索直接访问它并使用 Python 的 JSON 库将其解码为 Python 结构。例如:

from bs4 import BeautifulSoup
import requests
import json

headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'}
url = 'https://www.drogasil.com.br/fralda-huggies-tripla-protecao-tamanho-m.html'
req = requests.get(url, headers=headers)
soup = BeautifulSoup(req.content, 'html.parser')

script = soup.find('script', type='application/ld+json')
data = json.loads(script.text)

title = data['name']
total_price = data['offers']['price']

quantity = soup.find("li", class_="quantity").get_text().strip()

print(title)
print(quantity)
print(total_price)

给你:

HUGGIES FRALDAS DESCARTAVEL INFANTIL TRIPLA PROTECAO TAMANHO M COM 42 UNIDADES
42 Tiras
38.79

我建议您添加 print(data) 以查看还有哪些可用信息。