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

使用Selenium通过XPath获取价格列表后无法打印文本的问题

解决Selenium打印价格文本而非WebElement对象的问题

你遇到的问题很常见——find_elements_by_xpath()返回的是WebElement对象的列表,直接打印这些对象自然会输出它们的会话和元素ID信息,而不是你想要的价格文本。要获取元素里的文本内容,只需要调用WebElement的.text属性就可以了。

修正后的代码(两种写法)

写法一:保留你原有的遍历逻辑

price = driver.find_elements_by_xpath("//div[@class='price']")
for x in range(len(price)):
    # 调用.text属性提取元素内的文本内容
    print(price[x].text)
driver.quit()

写法二:更简洁的直接遍历元素(推荐)

Python支持直接遍历列表中的元素,不用通过索引,代码可读性更好:

price = driver.find_elements_by_xpath("//div[@class='price']")
for item in price:
    print(item.text)
driver.quit()

特殊情况补充

如果遇到价格文本是通过JavaScript动态渲染的场景,.text可能无法正确获取内容,这时候可以尝试用get_attribute('innerText')或者get_attribute('textContent')替代,示例代码:

print(item.get_attribute('innerText'))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 14:22:55