pycharm Python - Selenium自动选项卡在执行后自动关闭

pvabu6sv  于 5个月前  发布在  PyCharm
关注(0)|答案(2)|浏览(85)

我是python的新手,试图用python学习Selenium。但是当我执行代码时,标签打开并在加载url后自动关闭。我从来没有遇到过这个问题,用java使用selenium。有人能给我一些解决方案吗
这里的代码

from selenium import webdriver
from selenium.webdriver.chrome.service import Service

ser_obj = Service("D:\\Python\\chromedriver-win64\\chromedriver.exe")
driver = webdriver.Chrome(service=ser_obj)
driver.get("https://gmail.com")

字符串

brc7rcf0

brc7rcf01#

在测试执行结束后不退出浏览器可以通过将detach添加到实验选项来实现。

from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options)

driver.get("https://gmail.com")

字符串
另一种(不太好的)方法是:

  • 在调试模式下运行测试,在要停止的行上添加空print()并添加断点(在IDE中)
  • 在希望脚本执行停止的行后添加time.sleep(1000)
ruyhziif

ruyhziif2#

这是因为你的Python脚本在执行完你的命令后会关闭。你可以添加input("Press enter to quit")来阻止这种关闭。

from selenium import webdriver
from selenium.webdriver.chrome.service import Service

ser_obj = Service("D:\\Python\\chromedriver-win64\\chromedriver.exe")
driver = webdriver.Chrome(service=ser_obj)
driver.get("https://gmail.com")

# This line of code will stop the python interpreter from closing. 
# which in turn will stop your selenium browser from closing as well.
input("Press enter to close the interpreter.")

字符串
请尝试一下,让我知道它是否有帮助。

相关问题