Selenium之没有操作后浏览器关闭

遇到的问题

浏览器没有会话后,自动关闭。

在写一个登录脚本时,登录失败进行断言,登录成功进入系统。在登录成功这部分功能时,运行结束后浏览器自动关闭,运行窗口也没有出现报错提示。

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
import time

class Base:
    def __init__(self, driver):
        self.driver = driver

    def base_input(self, locator, value):
        element = self.driver.find_element(*locator)
        element.clear()
        element.send_keys(value)

    def base_click(self, locator):
        self.driver.find_element(*locator).click()

def shut_down(driver, should_quit: bool) -> None:
    print(f"shut_down called with should_quit = {should_quit}")
    if should_quit:
        print("Closing the browser")
        driver.quit()
    else:
        print("Not closing the browser")

def get_login(username, password, should_quit: bool):
   

    # 启动浏览器
    driver = webdriver.Chrome()
    print("Browser started")
    driver.get("http://127.0.0.1:8234/login.html")
    driver.implicitly_wait(10)

    base = Base(driver)
    # 登录
    if username is not None:
        base.base_input((By.ID, "username"), username)
    if password is not None:
        base.base_input((By.ID, "password"), password)
    base.base_click((By.ID, "loginBtn"))
    time.sleep(2)

    try:
        alertText = driver.switch_to.alert.text
        print(f"Alert text: {alertText}")
        return alertText
    except Exception as e:
        print(f"Exception caught: {e}")
        return None
    finally:
        # 调试信息
        print(f"Finally block executing with should_quit = {should_quit}")
        # 无论是否捕获到异常,都会执行这里
        shut_down(driver, should_quit)
        if not should_quit:
            input("Press Enter to close the browser manually...")

# 调用示例
result = get_login('byhy', 'sdfsdf', False)
print(result)

#当时的代码

一顿调试后发现,原来是WebDriver的机制问题。默认情况下,当 WebDriver 会话结束时,浏览器窗口会自动关闭。通过设置 "detach" 选项为 True,可以防止这种情况发生。

 options = Options()
 options.add_experimental_option("detach", True)  # 保持浏览器打开

    # 启动浏览器
    driver = webdriver.Chrome(options=options)

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值