当前位置:   article > 正文

Selenium根据Chrome浏览器版本自动下载/更新驱动chromedriver.exe

chromedriver.exe

个人经常使用到selenium来控制浏览器进行相关的操作,但是Chrome浏览器经常会自动更新,导致已有的驱动程序chromedriver.exe失效,需要重新下载。

以前尝试过禁止Chrome浏览器更新,但是这并不是很好的解决方案。

于是换了个方向,既然Chrome浏览器会自动更新,那么在我使用selenium控制浏览器时,也进行自动更新驱动程序

官方下载速度太慢,这里使用的是淘宝NPM镜像地址CNPM Binaries Mirrorhttps://registry.npmmirror.com/binary.html?path=chromedriver/

首先通过selenium尝试启动Chrome浏览器,如果异常再做对应的处理,就当前项目主要有两个异常:

  1. 驱动文件不存在:

    selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH.

  2. 驱动文件与当前浏览器不兼容:

    selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 101 Current browser version is 113.0.5672.64 with binary path C:\Program Files\Google\Chrome\Application\chrome.exe

然后根据对应的异常捕获本地已安装的Chrome浏览器的版本,然后进行下载/更新

驱动程序chromedriver.exe版本号一般为4个字段(113.0.5672.24),使用正则匹配前3个字段,最后一位使用最小的版本号

 最后拼接对应版本号驱动程序的下载链接,下载并解压驱动文件,完成自动下载/更新操作。

 完整代码:

  1. import os
  2. import re
  3. import sys
  4. import winreg
  5. import requests
  6. from zipfile import ZipFile
  7. from selenium import webdriver
  8. from selenium.common.exceptions import WebDriverException, SessionNotCreatedException
  9. def download_webdriver(driver_version):
  10. """
  11. 下载更新驱动\n
  12. 驱动下载网址:https://registry.npmmirror.com/binary.html?path=chromedriver/
  13. """
  14. # 获取驱动列表
  15. version_list = requests.get("https://registry.npmmirror.com/-/binary/chromedriver/").json()
  16. version_list = [version["name"] for version in version_list]
  17. # 获取符合的驱动版本号
  18. target_version = driver_version.rsplit(".", 1)[0] # 112.0.5615.28 >>> 112.0.5615
  19. for version in version_list:
  20. result = re.match(f"{target_version}.\d+", version)
  21. if result != None:
  22. target_version = result.group(0)
  23. print(f"目标驱动程序版本: {target_version}")
  24. # 下载驱动压缩包
  25. download_url = f"https://cdn.npmmirror.com/binaries/chromedriver/{target_version}/chromedriver_win32.zip"
  26. res = requests.get(download_url, stream=True)
  27. file_size = int(res.headers.get('Content-Length')) # 获取文件总大小(字节)
  28. file_size_MB = file_size / 1024 / 1024
  29. with open('./chromedriver_win32.zip', 'wb') as fwb:
  30. n = 1
  31. for chunk in res.iter_content(int(file_size / 10) + 1): # 每次遍历的块大小
  32. fwb.write(chunk)
  33. schedule = "████" * n + " " * (10 - n)
  34. print(f"进度: {10*n}% |{schedule}| {(file_size_MB/10)*n:.2f}MB/{file_size_MB:.2f}MB", end='\r')
  35. n += 1
  36. # 解压驱动压缩包
  37. with ZipFile("./chromedriver_win32.zip") as file:
  38. file.extract("chromedriver.exe", ".")
  39. os.remove("./chromedriver_win32.zip")
  40. print("\n下载/更新完成!")
  41. def create_webdriver(options=None):
  42. """
  43. 判断浏览器驱动是否正常\n
  44. return:浏览器驱动对象
  45. """
  46. while True:
  47. try: # 判断驱动是否正常
  48. driver = webdriver.Chrome(options=options)
  49. return driver
  50. except SessionNotCreatedException as msg: # 驱动与浏览器版本不一致
  51. driver_version = re.search("Chrome version (\d+)", str(msg)).group(1)
  52. chrome_version = re.search("Current browser version is ([\d.]+) with", str(msg)).group(1)
  53. print(f"SessionNotCreatedException: 浏览器版本与驱动程序不兼容,浏览器({chrome_version}),当前驱动程序({driver_version})\n正在更新驱动程序...")
  54. download_webdriver(chrome_version)
  55. except WebDriverException as msg: # 缺少驱动文件
  56. # 获取本机Chrome浏览器的版本
  57. key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Google Chrome')
  58. chrome_version = winreg.QueryValueEx(key, 'DisplayVersion')[0] # Version
  59. print(f"WebDriverException: 缺少浏览器对应的驱动程序,浏览器({chrome_version})\n正在下载驱动程序...")
  60. download_webdriver(chrome_version)
  61. except Exception as msg:
  62. print(msg)
  63. sys.exit(1)
  64. if __name__ == "__main__":
  65. options = webdriver.ChromeOptions()
  66. options.add_experimental_option('excludeSwitches', ['enable-logging'])
  67. driver = create_webdriver(options)
  68. print(111)
  69. driver.quit()

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/508473
推荐阅读
  

闽ICP备14008679号