Python Selenium脚本无语法错误但登录失效,浏览器自动关闭
问题分析与解决
问题代码
from selenium import webdriver from selenium.webdriver.common.by import By driver = webdriver.Chrome() driver.get("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login") driver.implicitly_wait(5) username ="//input[@placeholder='Username']" password ="//input[@placeholder='Password']" driver.find_element(By.XPATH, username).send_keys("Admin") driver.find_element(By.XPATH, password).send_keys("admin123") driver.find_element(By.XPATH, "//button[normalize-space()='Login']").click() print("Test pass")
问题现象
上述脚本未包含driver.close()或driver.quit()语句,但Chrome浏览器仍自动关闭,无法停留在登录后的页面。原本期望输入登录凭据后进入系统首页,实际却是浏览器直接关闭。
原因
Python脚本执行完毕后,程序进程会终止,webdriver.Chrome()创建的driver对象会被Python的垃圾回收机制销毁,关联的Chrome浏览器进程也会随之关闭。
解决办法
方法1:添加阻塞语句,维持脚本进程活跃
在脚本末尾添加input()或time.sleep(),阻止脚本立即结束,从而保留浏览器进程:
from selenium import webdriver from selenium.webdriver.common.by import By import time driver = webdriver.Chrome() driver.get("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login") driver.implicitly_wait(5) username ="//input[@placeholder='Username']" password ="//input[@placeholder='Password']" driver.find_element(By.XPATH, username).send_keys("Admin") driver.find_element(By.XPATH, password).send_keys("admin123") driver.find_element(By.XPATH, "//button[normalize-space()='Login']").click() print("Test pass") # 等待用户输入后再结束脚本,保留浏览器 input("按任意键关闭浏览器...") # 也可设置固定等待时长,比如10秒 # time.sleep(10) # 可选:手动调用quit关闭浏览器 driver.quit()
方法2:用with语句管理driver生命周期(配合阻塞)
with语句会自动处理资源回收,但要保持浏览器打开仍需添加阻塞语句:
from selenium import webdriver from selenium.webdriver.common.by import By with webdriver.Chrome() as driver: driver.get("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login") driver.implicitly_wait(5) username ="//input[@placeholder='Username']" password ="//input[@placeholder='Password']" driver.find_element(By.XPATH, username).send_keys("Admin") driver.find_element(By.XPATH, password).send_keys("admin123") driver.find_element(By.XPATH, "//button[normalize-space()='Login']").click() print("Test pass") input("按任意键关闭浏览器...")
内容的提问来源于stack exchange,提问作者Pradnya Deshpande
相关产品推荐
相关产品推荐

