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

Selenium使用find_elements无法获取全部section元素的求助

解决Selenium无法获取全部section元素的问题

核心问题分析

  • 定位目标错误:你要提取的是section元素,但代码里却在查找div元素,直接导致无法获取目标对象。
  • 绝对路径范围错误:从flights[18]调用find_elements时,使用绝对XPATH会从整个文档根节点重新查找,而非限定在该元素的子节点范围内,这是只拿到第一个元素的关键原因。
  • 固定索引易失效:代码中依赖flights[18]、li[19]这类固定索引定位元素,页面结构稍有变化就会出错。

修正后的代码

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager

url = "https://www.latamairlines.com/us/en/flight-offers?origin=BOG&inbound=2024-07-15T12%3A00%3A00.000Z&outbound=2024-07-01T12%3A00%3A00.000Z&destination=MDE&adt=1&chd=0&inf=0&trip=RT&cabin=Economy&redemption=false&sort=RECOMMENDED"

options = webdriver.ChromeOptions()
options.add_argument('--incognito')

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
driver.get(url)

# 处理弹窗(改用部分类名匹配,避免依赖动态生成的完整类名)
WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.XPATH, './/button[contains(@class, "lmJCPj")]'))
).click()

# 等待航班列表加载完成
flight_list = WebDriverWait(driver, 10).until(
    EC.presence_of_all_elements_located((By.XPATH, '//ol[@data-testid="flight-offers-list"]/li'))
)

# 定位目标航班的展开按钮
target_flight = flight_list[18]  # 暂时保留索引,建议后续根据航班具体信息定位
expand_btn = WebDriverWait(target_flight, 10).until(
    EC.element_to_be_clickable((By.XPATH, './/a[contains(@class, "flight-details-link")]'))
)
expand_btn.click()

# 等待弹窗中的所有section元素加载完成
itinerary_sections = WebDriverWait(driver, 10).until(
    EC.presence_of_all_elements_located((By.XPATH, '//dialog//section'))
)

# 输出结果
print(f"找到{len(itinerary_sections)}个section元素")
for idx, section in enumerate(itinerary_sections):
    print(f"第{idx+1}个section内容摘要:{section.text[:100]}...")

driver.quit()

关键修改说明

  • 修正目标元素:直接定位section元素,确保获取你需要的对象。
  • 使用相对路径:子元素查找时XPATH以.开头,限定查找范围为当前元素的子节点。
  • 优化等待逻辑:用presence_of_all_elements_located确保所有目标元素加载完成后再获取。
  • 降低动态类名依赖:用contains(@class, "xxx")匹配部分类名,避免前端动态类名变化导致定位失效。

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

相关产品推荐
方舟 Agent Plan

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

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