selenium自动配置webdriver,支持chrome
2020-10-11 本文已影响0人
Aedda
版本3 更新日期2022年3月10日
import subprocess
import winreg
from urllib import request
import zipfile
class Plugin:
def plugin_inspect_chromedriver(self, driver_path: str = ''):
chrome_v = self.get_chrome_version()
driver_v = self.get_driver_version(driver_path)
if chrome_v == driver_v: return
url = f'http://npm.taobao.org/mirrors/chromedriver/{chrome_v}/chromedriver_win32.zip'
zip_file = driver_path.replace('.exe', '.zip')
self.download(url, zip_file)
file = zipfile.ZipFile(zip_file, 'r')
file.extractall(path=os.path.dirname(zip_file))
file.close()
os.remove(zip_file)
@staticmethod
def download(file_url: str, save_path: str):
file_url = file_url.replace(' ', '%20').replace('—', '%E2%80%94')
request.urlretrieve(file_url, save_path)
@staticmethod
def get_chrome_version():
try:
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Google\Chrome\BLBeacon')
_v, temp = winreg.QueryValueEx(key, 'version')
return _v
except WindowsError as e:
return e
@staticmethod
def get_driver_version(driver_path):
cmd = f'{driver_path} --version' # 拼接成cmd命令
try:
out, err = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
out = out.decode('utf-8')
_v = out.split(' ')[1]
return _v
except IndexError as e:
return e