Selenium无法爬取span标签中的商品价格问题求助
解决Selenium无法爬取商品价格的问题
问题根源分析
- 未获取元素文本:你当前代码直接打印
product_price元素对象,而非其文本内容,只会输出元素内存地址等信息,看不到实际价格。 - 缺少显式等待:页面可能采用动态渲染,价格元素加载滞后于标题和SKU,直接调用
find_elements可能捕获不到已加载的元素。 - 选择器精度不足:原CSS选择器
.price-box .price可能匹配到非目标元素,层级不够精准。
修正方案
1. 添加显式等待
使用WebDriverWait等待价格元素加载完成,确保元素已渲染到DOM中。
2. 调整选择器
用更精准的选择器定位商品卡片内的价格元素,比如.product-item-details .price,避免匹配页面其他无关的.price元素。
3. 获取元素文本内容
通过.text属性获取价格的实际文本值。
修正后的代码
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Firefox() driver.get('https://www.kurtadler.com/greenery/wreaths.html') # 显式等待元素加载,设置10秒超时 wait = WebDriverWait(driver, 10) product_prices = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, '.product-item-details .price'))) product_titles = wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'product-item-link'))) product_skus = wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'product-item-sku'))) # 打印商品标题 for title in product_titles: print(f"标题: {title.text.strip()}") # 打印商品SKU for sku in product_skus: print(f"SKU: {sku.text.strip()}") # 打印商品价格 for price in product_prices: print(f"价格: {price.text.strip()}") driver.quit()
额外说明
- 若页面存在多个价格(如示例中的拆分价和整箱价),可调整选择器区分:用
.split + .price获取拆分价,.case + .price获取整箱价。 - 确保浏览器驱动版本与Firefox版本匹配,避免版本不兼容导致的隐性问题。
内容的提问来源于stack exchange,提问作者Arnold Schwartzkopf
相关产品推荐
相关产品推荐

