学习selenium的时候,上手第一个脚本发现成功打开浏览器后,代码执行完毕浏览器又秒关闭了,代码如下:

from  selenium import webdriver
 
driver = webdriver.Chrome()
driver.get("https://www.baidu.com")

1、检查代码,代码中没有写driver.quit()或driver.close()方法,也没有其它错误提示;

2、检查版本号,浏览器版本号python用selenium打开浏览器后秒关闭浏览器的解决办法,驱动版本号python用selenium打开浏览器后秒关闭浏览器的解决办法,确认版本号没有问题;

3、最后找到解决方法,如下:

from selenium import webdriver
 
options = webdriver.ChromeOptions()
options.add_experimental_option('detach', True)
 
driver = webdriver.Chrome(options=options)
driver.get('http://www.baidu.com')

python selenium默认情况下,执行完代码逻辑后,浏览器也会自动关闭,上述代码可以避免浏览器自动关闭。

python用selenium打开浏览器后秒关闭浏览器的解决办法

另一种更简便的写法:

from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options
 
opt = Options()
opt.add_experimental_option('detach', True)
# 通过option参数,设置浏览器不关闭
web = Chrome(options=opt)
web.get("https://www.lagou.com/")

总结

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。