谷歌浏览器在使用 selenium 启动后立即关闭

Google chrome closes immediately after being launched with selenium(谷歌浏览器在使用 selenium 启动后立即关闭)

本文介绍了谷歌浏览器在使用 selenium 启动后立即关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Mac OS X 上使用 selenium 和 python 3.6.3.

I am on Mac OS X using selenium with python 3.6.3.

这段代码运行良好,打开谷歌浏览器并且浏览器保持打开状态.:

This code runs fine, opens google chrome and chrome stays open.:

chrome_options = Options()
chrome_options.binary_location="../Google Chrome"
chrome_options.add_argument("disable-infobars");
driver = webdriver.Chrome(chrome_options=chrome_options)

driver.get("http://www.google.com/")

但是由于代码封装在函数中,浏览器在打开页面后立即终止:

But with the code wrapped inside a function, the browser terminates immediately after opening the page:

def launchBrowser():
   chrome_options = Options()
   chrome_options.binary_location="../Google Chrome"
   chrome_options.add_argument("disable-infobars");
   driver = webdriver.Chrome(chrome_options=chrome_options)

   driver.get("http://www.google.com/")
launchBrowser()

我想在保持浏览器打开的同时在函数中使用相同的代码.

I want to use the same code inside a function while keeping the browser open.

推荐答案

我的猜测是驱动程序会被垃圾收集,在 C++ 中,函数(或类)中的对象在脱离上下文时会被销毁.Python 的工作方式并不完全相同,但它是一种垃圾收集语言.不再引用的对象将被收集.

My guess is that the driver gets garbage collected, in C++ the objects inside a function (or class) get destroyed when out of context. Python doesn´t work quite the same way but its a garbage collected language. Objects will be collected once they are no longer referenced.

要解决您的问题,您可以将对象引用作为参数传递,或将其返回.

To solve your problem you could pass the object reference as an argument, or return it.

    def launchBrowser():
       chrome_options = Options()
       chrome_options.binary_location="../Google Chrome"
       chrome_options.add_argument("start-maximized");
       driver = webdriver.Chrome(chrome_options=chrome_options)

       driver.get("http://www.google.com/")
       return driver
    driver = launchBrowser()

这篇关于谷歌浏览器在使用 selenium 启动后立即关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:谷歌浏览器在使用 selenium 启动后立即关闭

基础教程推荐