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

使用Selenium实现可用座位自动选择的方案咨询

使用Selenium实现自动监控并选中可用座位

下面是基于Python的落地实现方案,你需要根据目标页面的实际HTML结构调整细节:

1. 环境准备

  • 安装Selenium:pip install selenium
  • 下载对应浏览器的驱动(比如ChromeDriver),确保驱动版本和浏览器版本匹配,可将驱动路径配置到系统环境变量,或在代码中直接指定路径。

2. 核心代码实现

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
import time

# 初始化Chrome浏览器(可替换为Firefox等其他浏览器)
options = webdriver.ChromeOptions()
# 可选:添加防检测参数,降低被网站识别为自动化工具的概率
options.add_argument("--disable-blink-features=AutomationControlled")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)

driver = webdriver.Chrome(options=options)
driver.get("你的目标座位页面URL")

try:
    while True:
        # 等待页面核心元素加载完成(根据实际页面调整等待目标)
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.CLASS_NAME, "seat"))  # 假设座位元素的统一class为seat
        )
        
        # 获取所有座位元素
        all_seats = driver.find_elements(By.CLASS_NAME, "seat")
        target_seat = None
        
        # 遍历筛选可用(绿色)座位
        for seat in all_seats:
            # 以下两种判断方式选其一,根据页面实际逻辑调整:
            # 方式1:通过class标识判断(比如可用座位额外带"available"类)
            if "available" in seat.get_attribute("class"):
                target_seat = seat
                break
            # 方式2:通过背景色判断(注意颜色值要和页面实际一致,可能是rgb或十六进制格式)
            # bg_color = seat.value_of_css_property("background-color")
            # if bg_color == "rgb(0, 255, 0)" or bg_color == "#00ff00":
            #     target_seat = seat
            #     break
        
        if target_seat:
            seat_id = target_seat.get_attribute("data-seat-no")  # 假设座位有编号属性
            print(f"找到可用座位:{seat_id},正在选中...")
            target_seat.click()
            break  # 完成选中后退出循环
        else:
            print("当前无可用座位,5秒后刷新页面...")
            time.sleep(5)
            driver.refresh()
            
finally:
    # 可选:操作完成后可选择保留浏览器或关闭
    # driver.quit()
    pass

3. 关键注意事项

  • 元素定位适配:必须用浏览器开发者工具(F12)查看目标页面的座位元素特征,修改代码中的选择器(比如By.CLASS_NAME可替换为By.XPATH、By.CSS_SELECTOR等)和可用座位的判断条件。
  • 刷新频率控制:不要设置过短的刷新间隔(建议3-10秒以上),避免触发网站反爬机制导致IP被限制。
  • 优先用显式等待:代码中用WebDriverWait等待元素加载,比强制time.sleep更可靠,能避免页面加载缓慢导致的元素查找失败。
  • 异常处理补充:可根据需求添加try-except块,处理页面加载失败、点击无效等异常情况,防止程序意外崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 19:03:28