본문 바로가기
Python/Python

Python) chrome driver 자동 다운로드 만들기

by 유노파이 2022. 1. 8.

이미 pip에 모듈화 되어있어서 다운받으면 끝

 

여러 버전을 다운 받을 경우가 있어서 모듈 설치후 참고하여 커스텀 하기로 결정

 

대충 확인해 보니

1.운영체제 확인 

2.버전 확인 후 requests를 이용해

3.최신 크롬드라이버를 다운로드

 

최종적으로 만들 크롬드라이버 다운로드 기능은..

1. 윈도우 버전으로만..

2. 여러버전 다운가능

3. chromedriver 설치 폴더 추가

# -*- coding: utf-8 -*-

import os
import sys
import re
import requests
from bs4 import BeautifulSoup
import zipfile


# 0 현재 최신버전
# 1 여러버전 지정
mode = 1

# 다운받을 버전 리스트
version_list = [95,96,97]

# 사용자 pc Downloads 폴더
down_path = os.path.expanduser("~")+"/Downloads"
    
# 크롬드라이버를 설치할 폴더
install_path = r"C:\Python27"

#------------------------------------------------------------------
def check_chrome_driver_version():
    # 크롬드라이버 버전 체크
    path_list = [
                    r"C:\Program Files\Google\Chrome\Application",
                    r"C:\Program Files (x86)\Google\Chrome\Application"
    ]
    
    for pa in path_list:
        for path ,dirs,files in os.walk(pa):
            for f in files:
                if f == "chrome_pwa_launcher.exe":
                    chromedriver_version = '.'.join(path.split('\\')[-1].split('.')[:3])
                    print ("--- chromedriver_version", chromedriver_version)
                    return chromedriver_version
                
# 버전 찾기
def parse_web():
    # current_chromedriver_version check
    current_chromedriver_version = check_chrome_driver_version()
    
    r = requests.get('https://chromedriver.chromium.org/downloads')
    source = BeautifulSoup(r.content,"html.parser")
    
    findVersion = source.find("div").text

    findVersion = findVersion.split(current_chromedriver_version)
    get_version = re.search("\d\d", findVersion[1]).group(0)
    
    down_chromedriver_version = current_chromedriver_version+"."+get_version
    print (down_chromedriver_version)
    return down_chromedriver_version

# 여러 버전 찾기
def find_version(version_list):
    r = requests.get('https://chromedriver.chromium.org/downloads')
    source = BeautifulSoup(r.content,"html.parser")
    
    source_text = source.find("div").text

    for ver in version_list:
        # 97.0.4692.36 패턴을 찾음
        c_version = re.search(str(ver)+".\d.\d\d\d\d.\d\d", source_text)
        print (c_version.group())
        yield c_version.group()

def start_download(chromedriver_version):

    # 다운할 폴더로 이동
    print (down_path)
    os.chdir(down_path)

    url_file = 'https://chromedriver.storage.googleapis.com/'
    file_name = "chromedriver_win32.zip"
    
    file = requests.get(url_file + chromedriver_version + '/' + file_name)

    # 응답코드
    return_code = file.status_code
    print (return_code)
    
    if return_code == 200:
        print ("--- successfully download")
    else:
        print ("--- failed download")
        return False
    
    with open(file_name, "wb") as code:
            code.write(file.content)

    return True
            
def down_chrome_driver(down_path):

    chromedriver_version = parse_web()

    start_download(chromedriver_version)
                
def copy_chrome_driver(down_path):
    print ("--- copy chromeDriver")
    chrome_zip = down_path+'/chromedriver_win32.zip'
    
    zipfile.ZipFile(chrome_zip).extract("chromedriver.exe", install_path)
    

def mutiple_down_chrome_driver(version_list, down_path):
    for chromedriver_version in find_version(version_list):
        if start_download(chromedriver_version):
            yield chromedriver_version
        else:
            yield False
            
def mutiple_copy_chrome_driver(version, down_path):
    print ("--- copy chromeDriver"+version+'\n')
    chrome_zip = down_path+'/chromedriver_win32.zip'

    to_path = install_path+'\\'+str(version.split('.')[0])

    # 없으면 폴더생성
    if not os.path.exists(to_path): 
        os.makedirs(to_path)       
        
    zipfile.ZipFile(chrome_zip).extract("chromedriver.exe", to_path)
        

# ------------- 실행 -------------
if __name__ == "__main__":

    if mode == 0: # 현재최신버전
        if down_chrome_driver(down_path): 
            copy_chrome_driver(down_path)
    else: # 여러버전
        for version in mutiple_down_chrome_driver(version_list, down_path):
            if version != False:
                mutiple_copy_chrome_driver(version, down_path)

댓글