たくまのブログ

たくまのブログ

皆さんに見て頂きたい反面、
ただの記録としても使います。

こんにちは、たくまです

 

前回も似たような記事を書きましたが、

Chromeのバージョンアップに伴い、正常動作しなかった為改良しました。

 

主要な部分のみ先に解説します

import subprocess

import re

 

def get_chrome_version():

    # Chromeのバージョン情報をレジストリから取得

    output = subprocess.run(

        r'reg query "HKEY_CURRENT_USER\Software\Google\Chrome\BLBeacon" /v version',

        capture_output=True, text=True, shell=True

    )

 

    # 正規表現を使用してバージョン番号を抽出

    match = re.search(r'version\s+REG_SZ\s+([\d.]+)', output.stdout)

    if match:

        return match.group(1)

    return None

この関数を使用すると、プログラムを実行したPCでChromeのバージョンが確認出来ます。

get_version = get_chrome_version()
driver_path = ChromeDriverManager(driver_version=get_version).install()
service = Service(driver_path)
driver = webdriver.Chrome(service=service, options=options)

このように記載すると、バージョンを指定して

ウェブドライバーのインストールが出来ます。

 

実際に使用しているものは

少し汚いですが、参考になれば幸いです。

 

 

# coding: utf-8

from selenium import webdriver

 

from selenium.webdriver.support.wait import WebDriverWait

from selenium.webdriver.chrome.options import Options

from selenium.webdriver.chrome.service import Service

from selenium.webdriver.support import expected_conditions as EC

from selenium.common.exceptions import NoAlertPresentException

from selenium.webdriver.common.by import By

from webdriver_manager.chrome import ChromeDriverManager

import requests

 

from cryptography.fernet import Fernet

import pandas as pd

import time

import os

 

import subprocess

import re

 

def get_chrome_version():

    # Chromeのバージョン情報をレジストリから取得

    output = subprocess.run(

        r'reg query "HKEY_CURRENT_USER\Software\Google\Chrome\BLBeacon" /v version',

        capture_output=True, text=True, shell=True

    )

 

    # 正規表現を使用してバージョン番号を抽出

    match = re.search(r'version\s+REG_SZ\s+([\d.]+)', output.stdout)

    if match:

        return match.group(1)

    return None

 

# 現在の秒数と小数点以下5桁を取得

seconds_remainder = f"{time.time() % 60:.5f}"

 

def copy_and_rename_file(original_file_path, new_name):

    # フォルダーパスを作成

    folder_path = original_file_path[:original_file_path.rfind('/')]

    # 新しいファイルのパスを作成

    new_file_path = os.path.join(folder_path, new_name)

    for try_num in [1,2,3]:

        try:

            # 元のファイルを読み取りモードで開き、新しいファイルをバイナリ書き込みモードで開く

            with open(original_file_path, 'rb') as src_file:

                with open(new_file_path, 'wb') as dst_file:

                    # 元のファイルの内容を新しいファイルに書き込む

                    dst_file.write(src_file.read())

                    break

        except:time.sleep(2)

    else:

        return original_file_path

 

    # 新しいファイルのパスを返す

    return new_file_path


 

options = Options()

options.add_argument('--headless')# ヘッドレス起動

#options.add_argument('--disable-gpu')

#options.add_experimental_option("prefs", {"download.default_directory":'%USERPROFILE%\Downloads'})#ダウンロード先

options.add_argument('--ignore-certificate-errors')# SSLエラー対策

options.add_argument('--disable-blink-features=AutomationControlled')# webdriver検出を回避

options.add_argument('--blink-settings=imagesEnabled=false')# 画像非表示


 

try:# 最新のバージョンのChromeドライバーを取得する

    driver_path = ChromeDriverManager().install()

    driver_path = copy_and_rename_file(driver_path, f'{seconds_remainder}.exe')

    service = Service(driver_path)

    driver = webdriver.Chrome(service=service, options=options)

except:

    try:

        latest_version = get_chrome_version()

        driver_path = ChromeDriverManager(driver_version=latest_version).install()

        driver_path = copy_and_rename_file(driver_path, f'{seconds_remainder}.exe')

        service = Service(driver_path)

        driver = webdriver.Chrome(service=service, options=options)

    except: # Chromeが失敗した時は、Edge

        from webdriver_manager.microsoft import EdgeChromiumDriverManager

        options = webdriver.EdgeOptions()

        #options.add_argument('headless')

        options.use_chromium = True  # EdgeドライバーがChromiumベースであることを指定

        options.add_argument('disable-blink-features=AutomationControlled')# webdriver検出を回避

        options.add_experimental_option("excludeSwitches", ["enable-automation"])

        options.add_experimental_option('useAutomationExtension', False)

        driver_path = EdgeChromiumDriverManager().install()

        service = Service(driver_path)

        driver = webdriver.Edge(service=driver_path, options=options)

 

driver.get("開きたいURLなど")

 

 

driver.quit()

os.remove(driver_path) # 複製したドライバーを削除する

Chromeが開けない場合は、Edgeを開くようにしています。

 

read_and_append_to_file

という関数で、ダウンロードされたウェブドライバーを複製し

os.removeで削除していますが

 

これは、もし重複して実行しても

ウェブドライバーが既に使われているエラーを回避する為です

 

 

 

 

 

 

これだけしても、恐らく

pythonのライブラリーアップデートをしないと

解決できない場合もあるでしょう。

 

完全に放置で長期運用するには、

ウェブドライバーは向いてないかもしれません。

 

 

 

 

 

 

 

 

ご清聴ありがとうございました。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

最近「ayn odin 2 pro」を買いましたが

リクエストあればブログにします!