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

Selenium爬取Kayak航班列表出现重复累加问题如何解决

问题原因
  • 打印逻辑错误:你在每次向detail_flights追加单条航班数据后就直接打印整个列表,而detail_flights是用来存储当前页面所有航班的容器,自然会出现长度逐次增加、内容累加的情况。
  • 索引逻辑错误:你先对j执行自增操作,再取elements[j]的属性,会直接跳过第一个航班元素,且循环到最后时j会等于元素列表长度,触发索引越界错误,你的空except块吞掉了这个报错导致你没有感知到。
  • 重复查询元素冗余:内层循环中每次都重新执行wd.find_elements_by_css_selector(".mainInfo")查询元素列表,页面滚动时如果触发动态加载,元素列表会发生变化,会导致索引错位。
修复方案

如果你的预期是得到[[航班1信息], [航班2信息], ...] 这种每个子列表仅含单条航班的结构,直接修改内层循环的存储、打印逻辑即可,修复后代码如下:

from selenium import webdriver # 补全原代码缺失的导入
from selenium.webdriver.chrome.options import Options # 补全原代码缺失的导入
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

list_link = ['https://www.kayak.it/flights/MIL-BCN/2021-09-02/2021-09-03/?sort=bestflight__a&fs=stops=0', 'https://www.kayak.it/flights/MIL-PMI/2021-09-02/2021-09-03/?sort=bestflight__a&fs=stops=0']

# 补全原代码缺失的chrome_options定义,规避反爬检测
chrome_options = Options()
chrome_options.add_argument('--disable-blink-features=AutomationControlled')
chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
chrome_options.add_experimental_option('useAutomationExtension', False)

wd = webdriver.Chrome('chromedriver',chrome_options = chrome_options)
wd.maximize_window()
wd.implicitly_wait(50)
wait = WebDriverWait(wd, 20)

# 定义总列表存储所有符合结构要求的结果
total_flights = []

for link in list_link:
  wd.get(link)
  try:
      wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[title='Accetta']"))).click()
  except:
      pass

  try:
      wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[id='onetrust-accept-btn-handler']"))).click()
  except:
      pass

  # 仅查询一次元素列表即可,避免动态加载导致索引错位
  elements = wd.find_elements_by_css_selector(".mainInfo")
  lngth = len(elements)
  if lngth == 0:
      print('Nothing more to scrape')
      continue
  
  for i in range(lngth):
      try:
          wd.execute_script("arguments[0].scrollIntoView(true);", elements[i])
          # 将单条航班包装为子列表存入总结果,符合预期结构
          single_flight = [elements[i].get_attribute('innerText')]
          total_flights.append(single_flight)
          # 直接打印单条子列表,不会出现内容累加
          print(single_flight)
      except Exception as e:
          print(f"第{i}条航班抓取失败:{e}")

# 可打印总结果验证结构
print("全部航班结果:", total_flights)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 02:27:03