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

2023-07-05Python开发问题
11

本文介绍了谷歌浏览器在使用 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 doesnt 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 启动后立即关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10

按10分钟间隔对 pandas 数据帧进行分组
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)...
2024-08-22 Python开发问题
11