selenium自动搭建
导入模块:
pip install webdriver_manager
pip install Selenium
webdriver_manager是 Python 中的一个库,用于管理 Web 驱动程序。它的作用是自动下载和设置不同浏览器(如 Chrome、Firefox、Edge 等)的 Web 驱动程序,以便在自动化测试中使用这些浏览器。
'''
import os
import shutil
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.firefox import GeckoDriverManager
from webdriver_manager.microsoft import EdgeChromiumDriverManager
def download_chromedriver():
'''下载谷歌浏览器驱动'''
folder_path = r'.\webdriver' # 需要存放驱动文件的路径
download_driver_path = ChromeDriverManager().install() # 使用ChromeDriverManager安装ChromeDriver,并获取驱动程序的路径
shutil.copy(download_driver_path, folder_path) # 复制文件到目标位置
print("自动安装driver的位置在:", download_driver_path)
# file_path = os.path.join(folder_path, 'chromedriver.exe') # 路径拼接
# driver = webdriver.Chrome(service=Service(file_path)) # 创建Chrome WebDriver,并指定驱动路径
# driver.get("https://www.baidu.com") # 打开百度网页
def download_firfoxdriver():
'''下载火狐浏览器驱动'''
folder_path = r'.\webdriver' # 需要存放驱动文件的路径
download_driver_path = GeckoDriverManager().install() #下载FirefoxDriver
shutil.copy(download_driver_path, folder_path) # 复制文件到目标位置
print("自动安装driver的位置在:", download_driver_path)
file_path = os.path.join(folder_path, 'geckodriver.exe') # 路径拼接
driver = webdriver.Firefox(file_path)
driver.get('https://www.baidu.com')
def download_edgedriver():
'''下载Edge浏览器驱动'''
folder_path = r'.\webdriver' # 需要存放驱动文件的路径
download_driver_path = EdgeChromiumDriverManager().install()
shutil.copy(download_driver_path, folder_path) # 复制文件到目标位置
print(download_driver_path)
# file_path = os.path.join(folder_path, 'msedgedriver.exe') # 路径拼接
# driver = webdriver.Edge(file_path)
# driver.get("https://www.baidu.com")
# download_chromedriver()
# download_firfoxdriver()
# download_edgedriver()