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

Selenium报错NoSuchWindowException问题求助(Chrome环境)

解决Selenium NoSuchWindowException报错的方案

报错原因分析

该错误多因Chrome用户配置目录无效、浏览器实例冲突,或代码参数配置错误导致浏览器窗口意外关闭。

具体解决步骤

  • 修正用户数据目录路径
    user-data-dir=directory 中的directory是占位符,需替换为本地真实的Chrome用户数据目录:

    • Windows:C:\Users\<你的用户名>\AppData\Local\Google\Chrome\User Data
    • Mac:~/Library/Application Support/Google/Chrome
    • Linux:~/.config/google-chrome
  • 修正配置文件目录参数
    --profile-directory=DRIVER存在两处问题:一是变量DRIVER未被解析,直接作为字符串传入;二是DRIVER值为chromedriver,并非Chrome配置文件夹名称。需改为实际配置文件夹名(如Profile 1),无需指定特定配置时可直接删除该行。

  • 避免调试端口冲突
    --remote-debugging-port=9222若被本地已有Chrome实例占用,会导致新窗口异常关闭。可更换端口号,或无需远程调试时直接删除该参数。

  • 确认驱动与浏览器版本匹配
    虽使用ChromeDriverManager自动安装驱动,仍需确认Chrome版本(110.0.5481.100)与ChromeDriver版本完全匹配,必要时手动下载对应版本驱动替换。

修正后的示例代码

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

# 替换为本地真实Chrome用户数据目录
USER_DATA_DIR = "C:\\Users\\你的用户名\\AppData\\Local\\Google\\Chrome\\User Data"
# 替换为实际配置文件夹名,无需则注释该行
PROFILE_DIR = "Profile 1"

chrome_options = Options()
chrome_options.add_argument(f'user-data-dir={USER_DATA_DIR}')
if PROFILE_DIR:
    chrome_options.add_argument(f"--profile-directory={PROFILE_DIR}")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
# 无需远程调试则删除该行,或更换端口
# chrome_options.add_argument("--remote-debugging-port=9223")

url = 'https://www.instagram.com/'
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options)
driver.maximize_window()
driver.implicitly_wait(10)
driver.get(url)
# 添加截图逻辑
driver.save_screenshot("instagram_screenshot.png")
driver.quit()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 20:15:09