Python 3.x 在函数中调用驱动程序时,如何在Python3中保持Selenium Webdriver浏览器的打开状态?
我有一个奇怪的问题,如果代码在函数或类中,我就不能保持chromewebdriver打开。即使我没有对驱动程序调用quit()函数 下面是函数Python 3.x 在函数中调用驱动程序时,如何在Python3中保持Selenium Webdriver浏览器的打开状态?,python-3.x,selenium,selenium-webdriver,browser,Python 3.x,Selenium,Selenium Webdriver,Browser,我有一个奇怪的问题,如果代码在函数或类中,我就不能保持chromewebdriver打开。即使我没有对驱动程序调用quit()函数 下面是函数 def driver_open(): mobile_emulation = {"deviceName": "iPhone 6"} chrome_options = webdriver.ChromeOptions() chrome_options.add_experimental_option("mobileEmulation", mob
def driver_open():
mobile_emulation = {"deviceName": "iPhone 6"}
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
driver = webdriver.Chrome(r"C:\Users\vaio\Dropbox\PyCharmProjects\Nagora\chromedriver.exe",
desired_capabilities=chrome_options.to_capabilities())
driver.get("https://www.youtube.com/")
return
但是,如果我在函数外部运行相同的代码段,浏览器将保持打开状态,使用类似以下的简单脚本:
mobile_emulation = {"deviceName": "iPhone 6"}
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
driver =webdriver.Chrome(r"C:\Users\vaio\Dropbox\PyCharmProjects\Nagora\chromedriver.exe",
desired_capabilities=chrome_options.to_capabilities())
driver.get("https://www.google.com/")
即使我在同一个python文件中运行这两段代码,Google页面浏览器仍然保持打开状态(因为代码在函数或类之外),而YouTube页面在DOM完成加载后自动关闭
我尝试了无数种解决方案,但都不起作用。函数定义以return结束,因此驱动程序变量也丢失了,但当您在函数外部执行此操作时,驱动程序定义仍然打开 解决方法是在启动chromedriver时使用“分离”选项 在您的情况下,添加:
chrome_options.add_experimental_option("detach", True)
同样的功能也可以使用IDE断点来实现,但不推荐使用。函数定义将以return关闭,因此驱动程序变量也将丢失,但当您在函数外部执行此操作时,驱动程序定义仍处于打开状态 解决方法是在启动chromedriver时使用“分离”选项 在您的情况下,添加:
chrome_options.add_experimental_option("detach", True)
使用IDE断点也可以实现相同的功能,但不推荐使用