疑念は探究の動機であり、探究の唯一の目的は信念の確定である。

数学・論理学・哲学・語学のことを書きたいと思います。どんなことでも何かコメントいただけるとうれしいです。特に、勉学のことで間違いなどあったらご指摘いただけると幸いです。 よろしくお願いします。くりぃむのラジオを聴くこととパワポケ2と日向坂46が人生の唯一の楽しみです。

PythonでChromeDriverを自動更新するプログラムを作った(再掲)。

概要
Seleniumchrome driverを使ってスクレイピングをおこなうが、Googleクロムのアプリは自動的に最新版となる。それによって、chrome driverのバージョンとクロムのバージョンが異なることによって、次のようなエラーが生じる。

selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 83

通常は最新のchrome driverをウェブ上からダウンロードして新しいchrome driverに替えなければならない。
今回はchrome driverを最新版のバージョンに自動的にアップデートするようなプログラムをrequestsBeautifulSoupなどを用いて作る。


プログラム

### import Selenium
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys

import subprocess
import re
import os
import urllib.request
import requests
from bs4 import BeautifulSoup

### get the current chrome version
def get_chrome_version():
    chrome = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'

    chrome_data = subprocess.run([chrome, '--version'], stdout=subprocess.PIPE, encoding='UTF-8')

    chrome_str  = chrome_data.stdout
    ch_reg_exp  = re.findall('\d+', chrome_str)
    ch_full_ver = '.'.join(ch_reg_exp)
    ch_int_ver  = ch_reg_exp[0]

    chrome_version = ch_full_ver, ch_int_ver

    return chrome_version


### download the suitable chrome driver
def download_chrome_driver(chrome_version):
    download_return = False
    download_dir = '/Users/USERNAME_XXXXX/Downloads'
    url = 'https://chromedriver.chromium.org/downloads'
    res   = requests.get(url)
    soup  = BeautifulSoup(res.text, 'html.parser')
    list_notes_txt = soup.find_all('a', href=re.compile('notes.txt'))

    download_url = None
    mac_file     = '/chromedriver_mac64.zip'
    for notes_txt in list_notes_txt:
        match = re.search(r'\d+', notes_txt.get('href'))
        if match.group(0) == chrome_version:
            notes_txt = notes_txt.get('href')
            download_url = os.path.dirname(notes_txt) + mac_file
            break

    if download_url != None:
        new_chrome_driver = download_dir + mac_file
        ### download
        urllib.request.urlretrieve(download_url, new_chrome_driver)

        ### unzip the file 'chromedriver_mac64.zip'
        subprocess.run(['unzip', new_chrome_driver], stdout=subprocess.PIPE, encoding='UTF-8')

        ### delete the zip file
        subprocess.run(['rm', new_chrome_driver])

        ### Because the unzipped chrome driver lies in the current directory, move it to the directory 'download_dir'
        subprocess.run(['mv', './chromedriver', download_dir])
        download_return = True

    return download_return

### change the new chrome driver
def change_new_chrome_driver():
    old_chrome_driver = '/Users/USERNAME_XXXXX/opt/anaconda3/lib/python3.7/site-packages/chromedriver_binary/chromedriver'
    new_chrome_driver = '/Users/USERNAME_XXXXX/Downloads/chromedriver'

    subprocess.run(['open', new_chrome_driver])
    subprocess.run(['rm', old_chrome_driver])
    subprocess.run(['mv', new_chrome_driver, old_chrome_driver])

### main
### Initialize Chrome
try:
    ### Success
    DRIVER_PATH = r'/Users/USERNAME_XXXXX/opt/anaconda3/lib/python3.7/site-packages/chromedriver_binary/chromedriver'
    options = Options()
    options.add_argument('--headless')

    driver = webdriver.Chrome(executable_path=DRIVER_PATH, options=options)

except Exception:
    #### Version Error
    ### STEP 1: get the current chrome version
    ret_val_1 = get_chrome_version()

    ### STEP 2: download the suitable chrome driver
    ret_val_2 = download_chrome_driver(ret_val_1[1])

    ### STEP 3: change the new chrome driver
    if ret_val_2 == True:
        change_new_chrome_driver()


プログラムの方針
STEP 1: 現在のGoogle Chromeのバージョンを取得する。
1.1: subprocessを使って、Chromeのバージョンを取得する。
ターミナル上で次のコマンドを打つと、現在使用中のChromeのバージョンがわかる。

$ Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --version
$ Google Chrome 87.0.4280.67

このコマンド操作をsubprocessを使って、Pythonのファイルでおこなう。

1.2: reを使って、取得したChromeの情報からバージョンの数値のみを取得する。
(87.0.4280.67, 87)


STEP 2: requestsBeautifulSoupで適切なバージョンのchrome driverを取得する。
2.1: バージョンに合うURLを取得する。
https://chromedriver.storage.googleapis.com/87.0.4280.88/chromedriver_mac64.zip

2.2: urllib.request.urlretrieveを使って、ダウンロードする(requestsでもできると思う)。

2.3: subprocessを使って、zip形式を解凍して、zipファイルを捨てる。


STEP 3: subprocessを使って、すでにあるchrome driverをDownloads配下にある最新のchrome driverに変更させる。

(だいたい完)