Google chrome closes immediately after being launched with 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 启动后立即关闭


- 使用 Cython 将 Python 链接到共享库 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01