随笔 - 148  文章 - 3  评论 - 2  阅读 - 11万

(selenium) 让浏览器在 webdriver 调用后保持打开状态

在使用 selenium 进行 webdriver 测试时,浏览器在调用完后将会自动关闭,即使没有调用 "driver.close()"。

有时候,可能需要特意将 浏览器保持开启状态,此时需要使用 detach 参数

# 'detach' = True 将不会自动关闭
options.add_experimental_option('detach', True)

具体示例代码如下:

复制代码
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService


options = webdriver.ChromeOptions()
pref_dict = {"profile.default_content_settings.popups": 0,
             # "download.default_directory": self.download_path,
             "safebrowsing.enabled": True
             }
options.add_experimental_option('prefs', pref_dict)
# 'detach' = True 将不会自动关闭
options.add_experimental_option('detach', True)

# 加载驱动,适配 selenium 4
chrome_service = ChromeService(executable_path=r"D:\Program Files (x86)\Python311\chromedriver.exe")
get_driver = webdriver.Chrome(options=options, service=chrome_service)


class WebService:
    def prepare_env(self, url):
        get_driver.get(url)


if __name__ == '__main__':
    sc = WebService()
    sc.prepare_env("http://www.baidu.com")
复制代码

 

posted on   bruce_he  阅读(1427)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示