遇到的问题
浏览器没有会话后,自动关闭。
在写一个登录脚本时,登录失败进行断言,登录成功进入系统。在登录成功这部分功能时,运行结束后浏览器自动关闭,运行窗口也没有出现报错提示。
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)