Python爬虫如何选择网站选项按钮获取点击后才显示的对应价格
问题原因
你当前使用的requests + BeautifulSoup组合只能获取页面初始加载的静态HTML内容,而目标站点的商品规格对应价格是由JavaScript动态渲染的:点击不同规格按钮时,前端JS会直接修改页面上展示的价格数值,这部分动态数据不会包含在初始的HTML响应中,所以你无法通过静态解析拿到对应规格的价格。
可行实现方案
方案1:使用Selenium模拟浏览器操作(逻辑直观,可直接复现点击选规格的操作)
这个方案通过启动真实浏览器模拟用户点击行为,拿到JS渲染完成后的页面数据,即便站点有反爬防护,通过率也更高。
首先安装依赖:
pip install selenium webdriver-manager
实现代码示例(以选择10g规格为例):
from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC URL = "https://deltaalternatives.com/product/bulk-delta-8-hemp-distillate-9pound-hammer/" # 自动配置Chrome驱动,不需要手动下载 driver = webdriver.Chrome(service=Service(ChromeDriverManager().install())) driver.get(URL) try: # 等待规格选项加载完成,点击10g对应的按钮 select_10g = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, "//div[text()='10 g']")) ) select_10g.click() # 等待价格更新后提取数值 price_element = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.CSS_SELECTOR, ".price bdi")) ) print("10g规格价格为:", price_element.text.strip()) finally: # 关闭浏览器 driver.quit()
方案2:解析页面内嵌的商品变体JSON数据(无需启动浏览器,运行效率更高)
该站点基于Woocommerce搭建,所有商品规格的价格、库存等数据会提前内置在页面的JS变量中,你可以直接用BeautifulSoup提取这段JSON数据,批量拿到所有规格的对应价格,不需要触发点击操作。
实现代码示例:
import requests from bs4 import BeautifulSoup import json import re URL = "https://deltaalternatives.com/product/bulk-delta-8-hemp-distillate-9pound-hammer/" headers = { "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:92.0) Gecko/20100101 Firefox/92.0" } page = requests.get(URL, headers=headers) soup = BeautifulSoup(page.content, "html.parser") # 提取包含商品变体数据的script标签 script_text = soup.find("script", string=re.compile("var wc_product_variable_params")).string # 用正则提取JSON数据段 json_data = re.search(r'var product_variations = (\[.*?\]);', script_text).group(1) variations = json.loads(json_data) # 遍历输出所有规格和对应价格 for item in variations: spec = item["attributes"]["attribute_pa_size"] price = item["display_price"] print(f"规格:{spec} 价格:${price}")
内容的提问来源于stack exchange,提问作者Nick Winston
相关产品推荐
相关产品推荐

