自动获取driver

chrome

下载驱动

1
2
3
4
5
6
7
8
9
10
11
12
13
@staticmethod
def down_driver(option):
'''
return: 返回driver,可以直接使用
'''
driver = webdriver.Chrome(
ChromeDriverManager(
url="https://registry.npmmirror.com/-/binary/chromedriver",
latest_release_url="https://registry.npmmirror.com/-/binary/chromedriver/LATEST_RELEASE",
cache_valid_range=365).install(),
options=option)
driver.delete_all_cookies()
return driver

下载2

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
32
33
34
35
36
37
38
@staticmethod
def determin_chrome_driver():

chrome_path = r'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe'


# 指定谷歌驱动目标位置
folder_path = os.path.join(ROOT_DIR, "env_setting")
# 驱动名称
file_name = 'chromedriver.exe'
# 路径拼接
file_path = os.path.join(folder_path, file_name)

if os.path.exists(file_path):
# 获取chromedriver.exe版本(谷歌浏览器驱动)
result = subprocess.run([file_path, '--version'], capture_output=True, text=True)
driverversion = '.'.join(result.stdout.strip().split(' ')[1].split('.')[:-1])

# 获取chrome.exe版本(谷歌浏览器)
command = f'wmic datafile where name="{chrome_path}" get Version /value'
result_a = subprocess.run(command, capture_output=True, text=True, shell=True)
output = result_a.stdout.strip()
chromeversion = '.'.join(output.split('=')[1].split('.')[0:3])

# 判断版本是否一致,不一致就重新下载
if driverversion != chromeversion:
# 使用ChromeDriverManager安装ChromeDriver,并获取驱动程序的路径
download_driver_path = ChromeDriverManager().install()
# 复制文件到目标位置
shutil.copy(download_driver_path, folder_path)
else:
print("版本一致,无需重新下载!")

else:
download_driver_path = ChromeDriverManager().install()
shutil.copy(download_driver_path, folder_path)

return file_path

edge

下载驱动

1
2
3
4
5
6
7
8
9
10
11
from webdriver_manager.microsoft import EdgeChromiumDriverManager

@staticmethod
def download_edgedriver():
'''
function:下载edge浏览器驱动
return: 返回一个下载的路径
'''
folder_path = EdgeChromiumDriverManager().install()
shutil.copy(folder_path, webDriver) # 拷贝folder_path到webDriver目录下
return folder_path

使用

1
2
# driver = webdriver.Edge(service=Service(下载路径))
driver = webdriver.Edge(service=Service(ddDriver.download_edgedriver()))

firefox

下载驱动

1
2
3
4
5
6
7
8
9
10
@staticmethod
def down_driver(option):
driver = webdriver.Firefox
(
service=FirefoxService(GeckoDriverManager(url="https://github.com/mozilla/geckodriver/releases/download",
latest_release_url="https://api.github.com/repos/mozilla/geckodriver/"
"releases/latest",
cache_valid_range=365).install(),
options=option))
return driver