谷歌浏览器与硒启动后立即关闭 [英] Google chrome closes immediately after being launched with selenium

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

问题描述

我在Mac OS X上使用带有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()

这篇关于谷歌浏览器与硒启动后立即关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆