ChromeDriverManager:自动化管理chrome driver下载
当程序使用PyInstaller打包成exe后,执行exe时,会将解压的内容放在系统的临时目录中进行解压执行,由此使用默认的ChromeDriverManager配置无法完成下载,需要手动指定下载路径
pip show selenium >> 4.31.0
pip show webdriver_manager >> 4.0.2
指定driver下载位置
import os
import sys
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.core.driver_cache import DriverCacheManager
# 如果打包成exe程序,需要用到下面代码
if getattr(sys, 'frozen', False):
# 打包环境
current_dir = os.path.dirname(sys.executable)
else:
# 开发环境
current_dir = os.path.dirname(os.path.abspath(__file__))
# 指定下载位置root_dir
cache_manager = DriverCacheManager(root_dir=current_dir)
driver_path = ChromeDriverManager(cache_manager=cache_manager).install()
# 初始化浏览器
service = Service(executable_path=driver_path)
option = Options()
# 禁用SSL验证
option.add_argument('verify=False')
option.add_argument('--ignore-ssl-errors=yes')
option.add_argument('--ignore-certificate-errors')
# 使用无头浏览器
# option.add_argument('--headless')
# 禁用“浏览器正在被自动化程序控制”的提示
option.add_experimental_option("excludeSwitches", ["enable-automation"])
option.add_experimental_option('useAutomationExtension',False)
with webdriver.Chrome(options=option, service=service) as browser:
browser.set_window_size(1920, 1080) # 设置窗口大小
browser.get("https://www.baidu.com") # 访问网址