Python-webdriver_manager的简单使用
提前祝大家五一快乐(*^▽^*)
前言:
我们在使用Selenium做UI自动化时都需要手动去下载各个浏览器版本的webdriver,有时我们可能还会遇到跨操作系统去进行测试。
以及有时因浏览器自动升级等原因,导致我们不得再去更新对应版本的webdriver。
为了解决以上问题,webdriver-manager应运而生,它可以帮助我们自动识别当前运行环境下系统信息以及对应浏览器信息,自动下载对应webdriver。
一、下载
1、https://pypi.org/project/webdriver-manager/ (点击链接下载了解更多)
2、pip install webdriver-manager
二、使用
1、代码演示(Selenium 3)
# -*- coding:UTF-8 -*- from selenium import webdriver from time import sleep from webdriver_manager.chrome import ChromeDriverManager # Chrome from webdriver_manager.firefox import GeckoDriverManager # FireFox from webdriver_manager.microsoft import IEDriverManager, EdgeChromiumDriverManager # IE、Edge ''' 演示代码 ''' url = "https://pypi.org/project/webdriver-manager/" def wb_test(): # driver = webdriver.Chrome(ChromeDriverManager().install()) # Chrome # driver = webdriver.Firefox(GeckoDriverManager().install()) # FireFox driver = webdriver.Edge(EdgeChromiumDriverManager().install()) # Edge driver.maximize_window() try: sleep(1) driver.get(url) except: print("打开url失败") else: print("打开url成功") if __name__ == '__main__': wb_test()
2、补充(Selenium 4)
# -*- coding:UTF-8 -*- from selenium import webdriver def browser_type(bw_type, url): if bw_type == "Chrome": from selenium.webdriver.chrome.service import Service as ChromeService from webdriver_manager.chrome import ChromeDriverManager driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install())) driver.get(url) elif bw_type == "Edge": from selenium.webdriver.edge.service import Service as EdgeService from webdriver_manager.microsoft import EdgeChromiumDriverManager driver = webdriver.Edge(service=EdgeService(EdgeChromiumDriverManager().install())) driver.get(url) elif bw_type == "Firefox": from selenium.webdriver.firefox.service import Service as FirefoxService from webdriver_manager.firefox import GeckoDriverManager driver = webdriver.Firefox(service=FirefoxService(GeckoDriverManager().install())) driver.get(url) elif bw_type == "IE": from selenium.webdriver.ie.service import Service as IEService from webdriver_manager.microsoft import IEDriverManager driver = webdriver.Ie(service=IEService(IEDriverManager().install())) driver.get(url) if __name__ == '__main__': browser_type(bw_type="Chrome", url="https://pypi.org/project/webdriver-manager/")
3、执行效果