You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Selenium如何通过XPath获取HTML重复结构的第二组目标数据

问题原因

你遇到的相对XPath失效问题核心是网站违反HTML规范,重复使用了prices-table这个id属性。你写的//*[@id="prices-table"]默认匹配页面中第一个出现的该id元素,也就是无效数据所在的表格,因此无法拿到正确结果。

可行解决方案

方案1:指定索引取第二个价格表

XPath的索引从1开始计数,直接取第二个prices-table节点即可,对应三类数据的相对XPath如下:

  • 单瓶价格://*[@id="prices-table"][2]/div/table/tbody/tr[3]/td[2]/div
  • 每箱价格://*[@id="prices-table"][2]/div/table/tbody/tr[4]/td[2]/div
  • 每盎司价格://*[@id="prices-table"][2]/div/table/tbody/tr[5]/td[2]/div

方案2:限定父节点范围(更稳定,推荐)

观察到有效数据的价格表位于带active类的标签页节点div.tab-pane.active下,通过父节点限定范围,就算后续页面结构调整增加了重复表格,也不会定位错误:

  • 单瓶价格://div[contains(@class,"tab-pane active")]//*[@id="prices-table"]/div/table/tbody/tr[3]/td[2]/div
  • 每箱价格://div[contains(@class,"tab-pane active")]//*[@id="prices-table"]/div/table/tbody/tr[4]/td[2]/div
  • 每盎司价格://div[contains(@class,"tab-pane active")]//*[@id="prices-table"]/div/table/tbody/tr[5]/td[2]/div
代码示例
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
import re

# 初始化driver等前置操作略
driver = webdriver.Chrome()

# 显式等待目标价格表加载完成,避免动态加载导致返回None
wait = WebDriverWait(driver, 10)
price_table = wait.until(EC.presence_of_element_located(
    (By.XPATH, '//div[contains(@class,"tab-pane active")]//div[@id="prices-table"]')
))

# 基于价格表节点的相对路径提取数据,复用父节点更高效
price_per_bottle = price_table.find_element(By.XPATH, './div/table/tbody/tr[3]/td[2]/div').text.strip()
price_per_case = price_table.find_element(By.XPATH, './div/table/tbody/tr[4]/td[2]/div').text.strip()
cost_per_ounce = price_table.find_element(By.XPATH, './div/table/tbody/tr[5]/td[2]/div').text.strip()

# 清洗数据,仅保留价格数值
def clean_price(raw_text):
    price_match = re.search(r'\$\d+\.\d+', raw_text)
    return price_match.group() if price_match else None

cleaned_bottle = clean_price(price_per_bottle)
cleaned_case = clean_price(price_per_case)
cleaned_ounce = clean_price(cost_per_ounce)

# 后续写入电子表格逻辑略

内容的提问来源于stack exchange,提问作者wilconwel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 11:45:03