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 启动后立即关闭


基础教程推荐
- 修改列表中的数据帧不起作用 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 包装空间模型 2022-01-01
- 求两个直方图的卷积 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01