简体   繁体   English

在 python 脚本完成后保持 Selenium 浏览器打开

[英]Keeping Selenium browser open after python script completion

I'm working on a selenium project, but every time the script ends, the window automatically closes.我正在处理 selenium 项目,但每次脚本结束时,window 都会自动关闭。 I'd like to keep the window up, though, after the script closes.不过,在脚本关闭后,我想保持 window 正常运行。 I've googled this, and stackoverflow says to uses the following code to keep it open:我已经用谷歌搜索了这个,stackoverflow 说使用以下代码保持打开状态:

chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option("detach", True)
s = Service(CHROME_DRIVER_PATH)
driver = webdriver.Chrome(options = chrome_options,service=s)
driver.get(URL)

I've tried using this, but it doesn't work - the window still automatically closes as soon as the script ends.我试过使用它,但它不起作用——脚本结束后 window 仍然会自动关闭。 In fact I looked on the Chromedriver docs and it specifically says that using the detach option will still close the browser after the session is quit.事实上,我查看了Chromedriver 文档,它特别指出,在 session 退出后,使用分离选项仍会关闭浏览器。 I want to be able to keep the window open so that I can use the developer console to figure the next tags I need to code in for my script.我希望能够保持 window 处于打开状态,以便我可以使用开发人员控制台来确定我需要为我的脚本编写代码的下一个标签。 (ie, I have the script open a page for me, sign in for me, then I need to do actions after I sign in). (即,我让脚本为我打开一个页面,为我登录,然后我需要在登录后执行操作)。 Has anyone else here dealt with this or tried to do this?这里有其他人处理过这个问题或尝试过吗? Having this browser closing on me is driving me nuts., Yeah I could open the page in another instantiation of the browser but I don't want to do that.关闭这个浏览器让我发疯。是的,我可以在浏览器的另一个实例中打开页面,但我不想这样做。 I could use a while True at the end of my script or have the script sleep for a thousand seconds or something.我可以在我的脚本结束时使用一段时间 True 或者让脚本休眠一千秒之类的。 but that's inelegant and not the right way to go about it...但这是不雅的,不是 go 关于它的正确方法......

please try as following:请尝试如下:

from selenium import webdriver

ch_options=webdriver.ChromeOptions()
driver=webdriver.Chrome(executable_path=r'C:\chromedriver\chromedriver.exe',options=ch_options)
driver.get('https://www.google.com/?hl=es')

If this is only for development or debugging, maybe you can add an input command as this will keep the webdriver running until you call webdriver.quit() and then end the script.如果这仅用于开发或调试,也许您可以添加一个输入命令,因为这将使 webdriver 保持运行,直到您调用webdriver.quit()然后结束脚本。 Here is an example:这是一个例子:

# selenium code goes here
keyword = input("enter a character or press enter to continue")
webdriver.quit()

using time.sleep() will run out of time and basically you can't control when it will stop or if it takes too long.使用 time.sleep() 将耗尽时间,基本上你无法控制它何时停止或是否需要太长时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM