You need to enable JavaScript to run this app. Python Selenium定时随机点击保活爬虫会话的实现方法及相关方案咨询
优惠活动
大模型
产品
解决方案
定价
更多

Python Selenium定时随机点击保活爬虫会话的实现方法及相关方案咨询

Selenium 会话自动断连保活实现

随机位置点击保活逻辑

针对网页长时间无交互自动断开会话的问题,可在现有抓取循环中嵌入定时随机点击逻辑,全程和抓取流程同线程执行,避免Selenium的线程安全问题。可直接使用的改造后代码如下:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
import json
import random
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 TimeoutException
from selenium.webdriver.common.action_chains import ActionChains


def keep_alive_random_click(wait_seconds: int):
    """等待指定时长后,在页面安全区域执行随机点击"""
    time.sleep(wait_seconds)
    # 获取当前浏览器可视区域尺寸
    win_size = driver.get_window_size()
    # 生成避开页面边缘的随机坐标,降低误点业务按钮的概率
    click_x = random.randint(150, win_size["width"] - 150)
    click_y = random.randint(200, win_size["height"] - 100)
    # 移动到随机位置执行点击
    ActionChains(driver).move_by_offset(click_x, click_y).click().perform()
    # 重置鼠标偏移量,避免后续正常操作的坐标错位
    ActionChains(driver).move_by_offset(-click_x, -click_y).perform()


options = Options()
options.add_argument("user-data-dir=C:\\Users\\user\\AppData\\Local\\Google\\Chrome\\User Data")
driver = webdriver.Chrome(executable_path='C:/chromedriver.exe', options=options)
driver.maximize_window()
driver.get('URL')
time.sleep(15)

def find_button():
    # 定位目标iframe并切换上下文
    iframe = driver.find_element(By.XPATH, "//*[@id=\"root\"]/main/div[1]/div/div/section/div[1]/div/iframe")
    driver.switch_to.frame(iframe)
    try:
        button = WebDriverWait(driver, 15).until(EC.element_to_be_clickable((By.XPATH, '/html/body/div[1]/div[2]/div/div/div/div[3]/button')))
        if button:
            button.click()
    except TimeoutException:
        pass
    # iframe操作完成后切回主文档,否则后续主页面元素定位会直接报错
    driver.switch_to.default_content()
    # 点击主页面目标SVG元素
    WebDriverWait(driver, 15).until(EC.element_to_be_clickable((By.CSS_SELECTOR,'#root > div.css-1dskt1c.ev4oou50 > main > div.css-fxcew.eqhy1wt0 > div.css-1o0ko6s.ejzudwb1 > div.css-wp7h99.ebewhpb0 > section.css-n56t2b.e1bk88wc2 > header > div.css-8hdyh3.esmanvo0 > svg'))).click()
    # 持续抓取数据循环
    while True:
        info = driver.find_element(By.CSS_SELECTOR, '#root > div.css-1dskt1c.ev4oou50 > main > div.css-fxcew.eqhy1wt0 > div.css-1o0ko6s.ejzudwb1 > div.css-wp7h99.ebewhpb0 > section.css-conr1v.e1bk88wc2 > div > div > div.css-1t6u4d1.ezcyhjn1 > div.css-r8tf41.eyg06i70')
        result = info.text
        result = result.replace('\n', ' ')
        # 每隔30秒执行一次保活随机点击
        keep_alive_random_click(wait_seconds=30)
        dictionary = {"1st 12": result[6:22], "2nd 12": result[30:46]}
        json_dump = json.dumps(dictionary)
        print(json_dump)

find_button()

实现注意点

  • 随机点击的坐标刻意避开了页面上下左右边缘区域,减少误点导航、弹窗关闭按钮的概率
  • 点击完成后必须重置鼠标偏移量,否则后续所有ActionChains的操作都会基于错误的坐标计算,导致点错目标
  • 代码替换了原参考中已弃用的find_element_by_xxx系列旧API,适配Selenium4以上版本
  • 补充了iframe操作完成后切回主文档的逻辑,解决原代码中主页面元素定位失败的问题

其他低副作用的会话保活方案

随机点击虽然能满足需求,但仍存在误触发页面交互的风险,可根据实际页面的检测逻辑选择以下更稳定的方案:

  • 微滚动模拟
    执行逻辑:触发页面的scroll事件,完全不触发任何点击交互,代码为:
    driver.execute_script("window.scrollBy(0, 5); window.scrollBy(0, -5);")
    适合检测页面滚动行为的场景,无任何误操作风险。
  • JS原生心跳请求
    执行逻辑:先在浏览器开发者工具的网络面板中,找到页面待机状态下自动发送的会话心跳接口,直接在页面上下文执行fetch请求携带登录态调用该接口,完全不需要操作页面元素,是最稳定的零副作用方案,示例代码:
    def keep_alive_via_heartbeat():
        # 替换为实际抓取到的心跳接口地址
        driver.execute_script("""
        fetch('/api/session/heartbeat', {
            method: 'POST',
            credentials: 'include'
        })
        """)
    
  • 无点击鼠标移动模拟
    执行逻辑:触发页面的mousemove事件,不会触发任何按钮的点击逻辑,代码为:
    ActionChains(driver).move_by_offset(10, 10).move_by_offset(-10, -10).perform()
    适合检测鼠标活跃状态的场景,无交互副作用。

注意:所有保活逻辑必须和现有抓取流程在同一个线程中执行,Selenium WebDriver不支持跨线程操作driver实例,跨线程调用会导致命令队列错乱,反而触发会话断开。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.13 03:27:03