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

如何利用Selenium实现智能等待优化高尔夫tee-time订场程序

Selenium替换time.sleep的优化方案

核心方案:用显式等待替代固定延迟

这是解决网络波动导致冗余等待的最优方案,只在目标元素就绪后才执行操作,彻底避免无意义的等待。

  • 基础实现代码:
    借助WebDriverWait和expected_conditions模块,设置最长等待时长,直到元素满足预设条件(比如可点击、可见):
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.by import By
    
    # 示例:等待预订按钮可点击,最长等待10秒(可根据实际场景调整)
    wait = WebDriverWait(driver, 10)
    book_btn = wait.until(EC.element_to_be_clickable((By.ID, "your-book-btn-id")))
    book_btn.click()
    
  • 常用等待条件适配场景:
    • EC.element_to_be_clickable():适合点击按钮、链接的场景,确保元素可见且可交互
    • EC.visibility_of_element_located():等待元素完全显示(有尺寸且未隐藏),适合判断时段是否加载完成
    • EC.text_to_be_present_in_element():等待元素出现指定文本,可用来判断时段是否变为"可用"状态
    • EC.presence_of_element_located():仅等待元素存在于DOM中,不需要可见,适合提前获取后台加载的元素

进阶:自定义等待逻辑

如果默认条件无法满足需求(比如判断时段的特殊状态),可以自己写判断函数:

from selenium.webdriver.support.ui import WebDriverWait

def check_tee_time_available(driver):
    # 自定义逻辑:比如检查时段元素的class是否包含"available"标识
    tee_time_item = driver.find_element(By.CSS_SELECTOR, ".tee-time-slot")
    return "available" in tee_time_item.get_attribute("class")

# 等待时段可用,最长等待15秒
wait = WebDriverWait(driver, 15)
wait.until(check_tee_time_available)
# 执行预订操作

额外提速技巧

  • 优化Chrome启动参数:禁用图片、非必要JS,减少页面加载资源:
    from selenium.webdriver.chrome.options import Options
    
    chrome_options = Options()
    chrome_options.add_argument("--blink-settings=imagesEnabled=false")  # 禁用图片
    chrome_options.add_argument("--disable-extensions")  # 禁用浏览器扩展
    driver = webdriver.Chrome(options=chrome_options)
    
  • 调整页面加载策略:设置为eager,不需要等待所有资源加载完成,只要DOM就绪就可以操作:
    chrome_options.page_load_strategy = "eager"
    
  • 避免隐式等待混用:不要同时设置driver.implicitly_wait()和显式等待,两者叠加会导致等待时间变长。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 07:04:53