selenium不自动关闭chrome,selenium hello world

selenium不自动关闭chrome

用visual studio的话,右键,在终端运行。

python 复制代码
from selenium import webdriver
 
options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=options)
url = 'https://blog.csdn.net/longwo888'
driver.get(url)

代码运行结果:

代码1:chrome浏览器不会自动关闭

from selenium import webdriver

dr = webdriver.Chrome()

dr.get('https://www.baidu.com/')

代码2:chrome浏览器会自动关闭

from selenium import webdriver

def run():

dr = webdriver.Chrome()

dr.get('https://www.baidu.com/')

if name == 'main ':

run()

代码3:chrome浏览器不会自动关闭

from selenium import webdriver

def run():

global dr

dr = webdriver.Chrome()

dr.get('https://www.baidu.com/')

if name == 'main ':

run()

以上三种代码统一换成Firefox浏览器的话,均不会自动关闭浏览器。

分析原因:代码2运行完之所以会关闭chrome浏览器,是因为对应chrome浏览器厂家提供的浏览器源生驱动文件(chromedriver.exe)自身逻辑设置引起的,方法运行完会自动关闭回收方法中定义的局部变量dr。如果不想让自动关闭方法中的局部变量对象dr,可以像代码3那样在变量名称前加个global声明下这是全局变量dr,或者把dr的定义像代码1那样定义到方法体的外面相当于全局变量。

二、问题解决

selenium版本太高了,默认安装的是最新版本,将版本降低后,就不会自动关闭浏览器了(我原本安装的是4.8.2,卸载装了4.0.0)

卸载selenium:pip3 uninstall selenium

安装指定版本的selenium:pip3 install selenium==4.0.0 -i https://pypi.tuna.tsinghua.edu.cn/simple

相关推荐
测试界清流4 小时前
Selenium4+Pytest自动化测试框架
selenium·测试工具·pytest
czhc11400756635 小时前
LINUX 69 FTP 客服管理系统 man 5 /etc/vsftpd/vsftpd.conf
linux·运维·chrome
not coder7 小时前
Selenium 查找页面元素的方式
selenium·测试工具
先树立一个小目标7 小时前
react-pdf(pdfjs-dist)如何兼容老浏览器(chrome 49)
chrome·react.js·pdf
ACMSunny11 小时前
Chrome二级标签无法选中的解决方案
前端·chrome
学不会就看12 小时前
selenium学习实战【Python爬虫】
python·学习·selenium
CIb0la12 小时前
Ai自动补全编程工具:llama vscode
运维·开发语言·学习·测试工具·程序人生
402 Payment Required1 天前
serv00 ssh登录保活脚本-邮件通知版
运维·chrome·ssh
炫彩@之星1 天前
Chrome书签的导出与导入:步骤图
前端·chrome