涉及javascript元素的Python Web抓取

2024-04-29 11:01:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图得到的大小和股票信息,无论是缺货或库存。 https://limitededt.com/collections/footwear/products/adidas-originals-jonah-hill-superstar-fw7577

看起来我必须手动单击每个尺寸,按钮将显示“售完”或“添加到购物车”

我能够从HTML页面检索基本信息,但这看起来像是一个JS事件

当我点击尺寸时,url变为

https://limitededt.com/collections/footwear/products/adidas-originals-jonah-hill-superstar-fw7577?variant=32432939466823

还有其他“变量=32432949466823”

我在想,我可以手动找出变体是什么,然后使用request再次加载页面,然后尝试获取按钮信息,并确定它是否有库存

是否有任何替代方案,我可以要求一次,并与规模互动,以检查库存

url = "https://limitededt.com/collections/footwear/products/adidas-originals-jonah-hill-superstar-fw7577"

source = requests.get(url).text

soup = BeautifulSoup(source, 'lxml')

Tags: httpscom信息url库存collectionsproductshill
1条回答
网友
1楼 · 发布于 2024-04-29 11:01:07

通过查看浏览器中的“网络”选项卡,您会发现一个包含所有产品的JSON,您只需将.json添加到URL即可加载此数据。不过,这并不包含股票信息,因为这些数据是从shopify加载的,shopify似乎是总部位于渥太华的加拿大跨国电子商务公司。这些数据被加载到DOM中的一个脚本标记中,您可以使用BeautifulSoup轻松地提取它(尽管我并不真正使用它——我们可以简单地使用正则表达式)

from bs4 import BeautifulSoup
import requests
import re

# define both URLs: for the JSON and the actual website for the shopify stock
url = 'https://limitededt.com/collections/footwear/products/adidas-originals-jonah-hill-superstar-fw7577'
product_info = url + '.json'

# fetch both data sources
with requests.Session() as session:
    soup = BeautifulSoup(session.get(url).text, 'html.parser')
    swym = soup.find('script', {'id': 'swym-snippet'})
    info = session.get(product_info).json()

# this will contain all the products and their stock
products = dict()

# get the data for each product from the json
for variant in info['product']['variants']:
    products[variant['id']] = variant

# find the shopify data using a regular expression
regex = re.compile(r'SwymProductVariants\[[0-9]+\] = ({[^(;)]+)')
inventory = re.findall(regex, swym.text)

# add the inventory information to the previously constructed product dictionary
for inv in inventory:
    indices = [key.strip().split(':')[1] for index, key in enumerate(inv.split(',')) if index in [1, 5]]
    products[int(indices[0])]['stock'] = int(indices[1])

相关问题 更多 >