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

Selenium报错NoSuchWindowException:目标窗口已关闭问题求助

问题:Selenium爬取YouTube视频标题时出现NoSuchWindowException错误

我用Selenium写了一段爬取YouTube视频标题的Python代码,运行时总是报NoSuchWindowException错误,就算注释掉driver.close()也一样。代码和错误信息如下:

import pandas as pd
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC

# driver = webdriver.Chrome(options=chrome_options)

driver = webdriver.Chrome() 
path = "https://youtube.com"
driver.get(path)
# xpath for search box
x_path_for_box = "/html/body/ytd-app/div[1]/div/ytd-masthead/div[4]/div[2]/ytd-searchbox/form/div[1]/div[1]/input"
searching_point_box = driver.find_element(By.XPATH, value=x_path_for_box)
# user manual input
search_word = input("Enter the search keyword: ")
searching_point_box.send_keys(search_word)
# xpath for search button
x_path_search_button= "/html/body/ytd-app/div[1]/div/ytd-masthead/div[4]/div[2]/ytd-searchbox/button"
searchButton = driver.find_element(By.XPATH, value=x_path_search_button)
searchButton.click()

titles = driver.find_elements(By.XPATH, '//*[@id="video-title"]')

links = [] # for fetching video url

for i in titles:
    links.append(title.text)
    
print(links)

driver.close()

错误信息:

NoSuchWindowException: Message: no such window: target window already closed
from unknown error: web view not found
(Session info: chrome=111.0.5563.65)

解决方法

  • 修复变量名错误:循环里写的links.append(title.text)是错误的,循环变量是i,要改成links.append(i.text)。这个低级错误会触发NameError,中断代码执行后可能导致浏览器窗口状态异常,间接引发NoSuchWindowException。

  • 添加显式等待,等待页面元素加载完成:YouTube是动态页面,直接查找元素很可能因为页面未渲染完毕导致失败,进而引发窗口相关异常。用WebDriverWait等待关键元素出现:
    比如搜索后等待视频标题加载:

    titles = WebDriverWait(driver, 10).until(
        EC.presence_of_all_elements_located((By.XPATH, '//*[@id="video-title"]'))
    )
    

    搜索框和搜索按钮也应该用显式等待:

    searching_point_box = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, x_path_for_box))
    )
    searchButton = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, x_path_search_button))
    )
    
  • 替换绝对XPATH为更稳定的定位方式:你用的绝对XPATH完全依赖页面结构,只要页面有微小改动就会失效,元素查找失败后可能触发后续异常。建议改用相对定位:

    • 搜索框:By.CSS_SELECTOR, "input#search"
    • 搜索按钮:By.CSS_SELECTOR, "button#search-icon-legacy"
    • 视频标题:By.CSS_SELECTOR, "a#video-title"
  • 确保ChromeDriver与Chrome版本匹配:你的Chrome版本是111.0.5563.65,必须下载对应版本的ChromeDriver,版本不匹配会导致浏览器和驱动通信异常,出现窗口关闭错误。

  • 用driver.quit()替代driver.close():driver.close()只关闭当前窗口,若存在多窗口或会话残留会引发异常;driver.quit()会彻底终止浏览器会话,清理所有资源,减少异常概率。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 13:37:15