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

Selenium页面持续刷新问题:如何实现定时刷新并维持会话

问题解决方案:实现页面定时刷新并维持会话

核心问题分析

你的代码存在几个关键问题导致无法正常刷新和维持会话:

  • driver.refresh是方法引用,未执行调用,必须写成driver.refresh()才会触发页面刷新
  • 缺少定时等待逻辑,没有设置刷新间隔
  • 代码中存在拼写错误:expected_conditions应使用你导入的别名EC,BY.ID需改为By.ID
  • 循环逻辑不够严谨,未处理刷新后的会话稳定性

修正后的代码实现

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException, TimeoutException
import time

user_name = "username"
password = "password"
refresh_interval = 5  # 每隔5秒刷新一次,可按需调整

driver = webdriver.Chrome()
driver.get('https://mywebsite.com/boardslots.aspx?date=07%2F31%2F2022')

# 登录流程
element = driver.find_element(By.ID,"txtUsername")
element.send_keys(user_name)
element = driver.find_element(By.ID,"txtPassword")
element.send_keys(password)
element.send_keys(Keys.RETURN)

# 保存登录后的Cookie,用于维持会话(可选,若网站刷新后会话失效则启用)
login_cookies = driver.get_cookies()

while True:
    try:
        # 尝试查找Claim链接
        claim_link = driver.find_element(By.LINK_TEXT,"Claim")
        claim_link.click()
        
        # 等待提交按钮可点击并提交
        try:
            submit_btn = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable((By.ID, "btnSubmitSingle"))
            )
            submit_btn.click()
        except TimeoutException:
            print("未找到提交按钮,跳过提交步骤")
            
    except NoSuchElementException:
        # 未找到Claim链接,执行刷新
        print("未找到Claim链接,刷新页面...")
        # 若刷新后会话失效,重新注入Cookie
        # driver.delete_all_cookies()
        # for cookie in login_cookies:
        #     driver.add_cookie(cookie)
        driver.refresh()
        
    # 设置刷新间隔
    time.sleep(refresh_interval)

关键优化点说明

  • 定时刷新:通过time.sleep(refresh_interval)控制每次操作后的等待时间,实现固定间隔刷新
  • 方法调用修正:将driver.refresh改为driver.refresh(),确保刷新操作执行
  • 错误处理增强:添加TimeoutException处理元素等待超时的情况,避免程序崩溃
  • 会话维持方案:注释部分提供了Cookie保存与注入的逻辑,若网站刷新后会话自动失效,可取消注释启用该功能
  • 元素等待优化:使用element_to_be_clickable替代visibility_of_element_located,确保元素可交互后再执行点击操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 17:27:23