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

Python+Selenium操作Firefox时跨文件无法复用已登录旧窗口问题

错误根因

每个Firefox()实例化操作都会启动独立的火狐浏览器进程,不同进程之间的资源完全隔离。你在LudusLogin.login()里启动了第一个浏览器进程生成窗口句柄,又在Main.py里新启动了第二个浏览器进程,第二个进程无法识别第一个进程的窗口句柄,因此抛出NoSuchWindowException。

修复方案(当前import调用场景最优解)

不需要返回窗口句柄,直接将登录完成的driver实例返回给业务逻辑调用即可,两个模块复用同一个driver进程。

修改LudusLogin.py

# filename: LudusLogin
import os
from dotenv import load_dotenv
from selenium.webdriver import Firefox
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.expected_conditions import title_is
from selenium.webdriver.support.wait import WebDriverWait
import time


def login():
    # Firefox driver for running window
    driver = Firefox()

    # Going to website
    driver.get("website")

    WebDriverWait(driver, timeout=3).until(title_is("Meddelelser"))

    # Login with credentials from .env
    load_dotenv()

    usr = os.getenv("usr")
    passwd = os.getenv("passwd")

    usr_field = driver.find_element(By.CSS_SELECTOR, "#brugerIdField")
    passwd_field = driver.find_element(By.CSS_SELECTOR, "#kodeordField")

    usr_field.send_keys(usr)
    passwd_field.send_keys(passwd)
    passwd_field.send_keys(Keys.RETURN)

    # Closing messages
    time.sleep(2)
    close_btn_meddelelser = driver.find_element(By.CLASS_NAME, "v-window-closebox")
    close_btn_meddelelser.click()
    WebDriverWait(driver, timeout=3).until(title_is("Aktuelt"))

    # 直接返回登录完成的driver实例,不要只返回窗口句柄
    return driver

修改Main.py

# filename: Main.py
import LudusLogin
from selenium.webdriver.common.by import By
from selenium.webdriver.support.expected_conditions import title_is
from selenium.webdriver.support.wait import WebDriverWait

# 直接获取登录完成的driver,复用同一个浏览器进程
driver = LudusLogin.login()

skema_btn = driver.find_element(By.CSS_SELECTOR, "span.v-menubar-menuitem:nth-child(4)")
skema_btn.click()
WebDriverWait(driver, timeout=3).until(title_is("Skemaer"))
拓展:跨独立脚本复用浏览器方案

如果需要在两个完全独立、不存在import关系的脚本中复用同一个已登录的浏览器,可以用火狐调试端口挂载的方式实现:

  • 命令行启动火狐并指定调试端口:firefox.exe --remote-debugging-port=9222
  • 两个脚本都通过Selenium挂载到这个已启动的浏览器进程,不需要重复登录

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 16:45:03