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

使用Selenium Python点击按钮后浏览器自动关闭,无法跳转页面求助

问题分析与解决方案

问题根源

你的代码里,web_driver_conn是capture_domain函数内的局部变量,当函数执行完毕后,Python垃圾回收机制会销毁这个WebDriver实例,而Selenium的WebDriver在被销毁时会自动关闭关联的浏览器窗口,这就导致点击按钮后浏览器立刻关闭,无法看到目标页面。

解决方案

方案1:添加阻塞代码延长WebDriver生命周期

在点击按钮后加入阻塞逻辑,让程序暂停执行,直到用户手动触发关闭,以此保持浏览器窗口打开:

修改后的主代码:

import time
from selenium.webdriver.common.by import By
from Base_Class import base_class

class Majestic_Domain:
    def capture_domain():
        web_driver_conn = base_class.web_driver()
        web_driver_conn.get("https://tranco-list.eu/")
        CSV_Download = web_driver_conn.find_element(By.XPATH, '//body/main/div/div/a')
        time.sleep(10)
        CSV_Download.click()
        # 添加阻塞,防止浏览器立即关闭
        input("操作完成,按回车键关闭浏览器...")

Majestic_Domain.capture_domain()

方案2:使用显式等待+类实例管理WebDriver

用类实例保存WebDriver对象,配合显式等待更可靠地等待页面状态,同时延长实例生命周期:

import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from Base_Class import base_class

class Majestic_Domain:
    def __init__(self):
        self.web_driver_conn = base_class.web_driver()

    def capture_domain(self):
        self.web_driver_conn.get("https://tranco-list.eu/")
        # 显式等待元素可点击,替代固定sleep,更高效可靠
        CSV_Download = WebDriverWait(self.web_driver_conn, 10).until(
            EC.element_to_be_clickable((By.XPATH, '//body/main/div/div/a'))
        )
        CSV_Download.click()
        # 等待页面URL变化,确认跳转完成
        WebDriverWait(self.web_driver_conn, 15).until(
            EC.url_changes("https://tranco-list.eu/")
        )
        # 阻塞等待用户操作
        input("按回车键关闭浏览器...")

if __name__ == "__main__":
    crawler = Majestic_Domain()
    crawler.capture_domain()

方案3:配置ChromeDriver保留浏览器窗口(可选)

在基础类的web_driver函数中添加Chrome选项,让浏览器在驱动进程结束后保持打开,但注意这可能导致驱动进程残留,需要手动清理:

修改基础类代码:

from selenium import webdriver

def web_driver():
    options = webdriver.ChromeOptions()
    # 开启detach选项,让浏览器在驱动退出后不关闭
    options.add_experimental_option("detach", True)
    driver_conn = webdriver.Chrome(options=options)
    return driver_conn

关键注意事项

  • 显式等待(WebDriverWait)比固定的time.sleep更推荐,它能根据页面实际加载状态动态等待,避免不必要的延迟,也更稳定。
  • 局部变量销毁导致浏览器关闭是这类问题的常见原因,核心思路是延长WebDriver实例的存活时间。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 23:20:20