如何用Python Selenium提取span标签中的价格?
问题分析与解决
你犯的几个错误:
- XPath语法不完整:你的XPath表达式末尾缺少闭合的
],导致语法错误,无法定位元素。 - Class属性匹配错误:HTML中span的class是
item-price js-variant-price(两个类名用空格分隔),但你写成了item-price.js-variant-price(用点号连接),这会让XPath去匹配class属性值完全等于这个带点字符串的元素,而页面中不存在这样的元素。 - 未正确提取目标值:你要的是
content属性里的79.95,但当前代码仅完成了元素定位,没有提取对应的属性值;如果直接取元素文本,得到的是79,95 TL,并非你需要的数值。
修正后的代码:
首先修正元素定位,然后提取content属性:
# 方法1:精准匹配class属性(注意空格) prices2 = driver.find_element(By.XPATH, "//span[@class='item-price js-variant-price']") # 方法2:用contains匹配class,避免类名顺序变化导致定位失败 # prices2 = driver.find_element(By.XPATH, "//span[contains(@class, 'item-price') and contains(@class, 'js-variant-price')]") # 方法3:结合itemprop属性,定位更精准 # prices2 = driver.find_element(By.XPATH, "//span[@itemprop='price']") # 提取content属性的79.95 price_value = prices2.get_attribute('content') print(price_value) # 输出:79.95
内容的提问来源于stack exchange,提问作者DiegoEwin
相关产品推荐
相关产品推荐

