You need to enable JavaScript to run this app. Selenium使用multiprocessing时每个进程新开Chrome窗口问题求助
优惠活动
大模型
产品
解决方案
定价
更多

Selenium使用multiprocessing时每个进程新开Chrome窗口问题求助

问题原因分析
  • 子进程重复执行顶层代码:Windows系统下Python multiprocessing 默认使用spawn启动模式,每个新进程都会完整重导主模块,你把driver = uc.Chrome()写在模块顶层,子进程导入时会直接执行这行代码,自然会弹出新的Chrome窗口,同时重新跑一遍全局逻辑。
  • Selenium驱动无法跨进程传递:webdriver实例是绑定到创建它的进程的内核对象,跨进程传递序列化后的driver实例没有任何意义,子进程根本无法操作主进程创建的浏览器窗口。
最优解决方案

你的场景属于IO密集型任务(元素查询、键盘输入都是等待浏览器响应的IO操作),完全不需要用多进程,改用多线程即可实现并行,没有进程隔离的各种问题,效率也更高。
推荐用threading.Event代替multiprocessing.Value作为终止信号,代码更简洁也不需要加锁。

修正后的代码示例
import threading
import time
from undetected_chromedriver import v2 as uc 

def login(driver):
    # 登录逻辑保持不变
    some_code

def check_results(stop_event, driver):
    while not stop_event.is_set():
        var_to_check = driver.find_element_by_xpath(some_xpath).text
        if var_to_check != '':
            stop_event.set()
            break
        time.sleep(0.1)

def type_text(stop_event, driver):
    text = 'Some text i need to be typed out'
    some_element = driver.find_element_by_xpath(some_xpath)
    for letter in text:
        if stop_event.is_set():
            break
        some_element.send_keys(letter)
    print('Typing ended')

def do_exercise(driver):
    stop_event = threading.Event()
    # 启动两个线程,共享同一个driver实例
    check_thread = threading.Thread(target=check_results, args=(stop_event, driver))
    type_thread = threading.Thread(target=type_text, args=(stop_event, driver))
    
    check_thread.start()
    type_thread.start()
    
    check_thread.join()
    type_thread.join()
    
    results_of_typing = driver.find_element_by_xpath(some_xpath).text
    return results_of_typing

if __name__ == '__main__':
    # 所有全局执行的逻辑都放在main块内,避免导入时重复执行
    driver = uc.Chrome()
    with driver:
        driver.get('https://some_site.com/')
        login(driver)
        results = do_exercise(driver)
        print(results)
优化点说明
  • 所有会生成浏览器实例、发起请求的逻辑都放在if __name__ == '__main__'块内,避免导入时重复执行
  • 用多线程替代多进程,天然共享同一份内存空间,同一个driver实例可以在多个线程中调用(Selenium的webdriver是线程安全的)
  • 用threading.Event作为终止信号,不需要手动加锁,读写性能更高,打字速度不会受到检查逻辑的影响

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 09:15:07