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

使用Selenium与Python遍历TrueCar无序列表时无法正确获取车辆价格

解决Selenium爬取TrueCar车辆价格的定位问题

问题根源

你遇到的核心问题是没有在当前列表项的上下文内进行相对定位:

  • 用//开头的XPath是全局搜索,无论遍历到哪个li,都会返回页面中第一个匹配的价格元素
  • 动态拼接索引的绝对XPath不仅脆弱(页面结构稍有变化就失效),而且依然是全局搜索,同时可能因页面动态加载导致索引不匹配

解决方案

改用相对定位,并使用更稳定的元素特征(比如class属性)来定位价格,避免依赖超长绝对路径。

修改后的代码

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
from webdriver_manager.chrome import ChromeDriverManager

driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get("https://www.truecar.com/used-cars-for-sale/listings/bmw/m4/location-palm-desert-ca/")

# 显式等待列表加载完成,避免获取空列表
wait = WebDriverWait(driver, 10)
# 用更稳定的属性定位列表容器(TrueCar的车辆列表ul有data-test属性)
listing_section = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'ul[data-test="usedListingList"]')))
listings = listing_section.find_elements(By.TAG_NAME, "li")

for listing in listings:
    try:
        # 在当前列表项内,用class定位价格元素(相对定位,无需全局路径)
        price = listing.find_element(By.CSS_SELECTOR, '.vehicle-card-price').text
        print(price)
    except Exception as e:
        # 跳过加载异常的列表项
        continue

driver.quit()

关键优化点

  1. 显式等待:用WebDriverWait确保列表容器加载完成,避免因页面动态渲染导致的空列表问题
  2. 稳定的容器定位:通过data-test属性定位列表容器,比绝对XPath更抗页面结构变化
  3. 相对定位:在每个listing(li元素)上下文内搜索价格,CSS选择器默认支持相对定位,无需额外前缀;如果用XPath则需要以.//开头(比如.//div[contains(@class, "vehicle-card-price")])
  4. 异常处理:添加try-except跳过加载失败的列表项,避免程序中途崩溃

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 15:44:50