在使用selenium时碰到一个问题。
公司的电脑会自动升级谷歌浏览器,导致需要经常更新谷歌浏览器驱动。
正常情况下旧法是可以正常使用的,但是现在却出现了问题,那就是浏览器的版本更新到了116,但是驱动的版本却只到114,这令我不管是代码还是人手都无法解决问题,于是我去寻找了新法。
下载链接:谷歌浏览器驱动
def openweb(self):
path_dri = fr'C:\Users\{os.getlogin()}\Desktop\chromedriver.exe'
if not os.path.exists(path_dri):
self.getdriver()
self.warnpath(self.path_normal)
self.warnpath(self.path_repeat)
option = webdriver.ChromeOptions()
prefs = {'profile.default_content_settings.popups': 0,
'download.default_directory': self.path_download}
option.add_experimental_option('prefs', prefs)
try: #前面有复制驱动的代码(未写),所以一定有driver,只判断version
self.driver1 = webdriver.Chrome(chrome_options=option,executable_path=path_dri)
except Exception as e:
download_path = fr'C:\Users\{os.getlogin()}\Desktop'
print(e)
reg = "Current browser version is.+with"
chrome_version = re.search(reg, str(e)).group().replace("Current browser version is ", "").replace(" with","")
file_name = download_path + 'chromedriver_' + chrome_version + '.zip'
print("Chrome Version:" + chrome_version)
url = 'http://chromedriver.storage.googleapis.com/' + chrome_version + '/chromedriver_win32.zip'
print('正在下载文件:'+ url)
a=0
if not os.path.exists(path0): #无驱动
a=1
if a == 1:
print('更新驱动中...')
form_header = {"User-Agent": "Chrome/68.0.3440.106"}
response = requests.get(url=url, headers=form_header)
open(file_name, 'wb').write(response.content)
# 解压zip文件
self.unzip_file(file_name, download_path)
os.remove(file_name)
if not os.path.exists(os.path.split(path0)[0]):
os.makedirs(os.path.split(path0)[0])
shutil.copy(path_dri,os.path.split(path0)[0])
self.driver1 = webdriver.Chrome(chrome_options=option,executable_path=path_dri)
def unzip_file(self,src_file, dest_dir, *password):
if password:
password = password.encode()
zf = zipfile.ZipFile(src_file)
try:
zf.extractall(path=dest_dir, pwd=password)
except zipfile.BadZipFile as e:
print(e)
print(f'请检查{src_file}是否可以正常打开')
raise MyError
except RuntimeError as e:
print(e)
raise MyError
zf.close()
在群里问了一圈,得到了一个github链接
使用该库可以不必每次再自己更新驱动啦,并且该库也支持一些其他浏览器的驱动,这里截取谷歌浏览器驱动。
GitHub - SergeyPirogov/webdriver_manager
pip install webdriver-manager
# selenium 3
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(ChromeDriverManager().install())
# selenium 4
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))