LoginSignup
11
8
記事投稿キャンペーン 「2024年!初アウトプットをしよう」

Pythonで最新版のEdge Driverをダウンロードする方法

Last updated at Posted at 2024-01-09

概要

WebDriver for EdgeでRPAを利用していたら、ブラウザの自動更新が行われてしまった事でエラーが発生ことに悩まされましたことがあります。PythonでEdge Driverをダウンロードモジュールを作成しました。

開発環境

OS: Windows
Pythonバージョン:3.8.2
IDE: PyCharm Community Edition 2022.3

ソース

以下のソースを作成しました。


import requests
from bs4 import BeautifulSoup
import zipfile
import os

def download_file(target_url, filepath, dest_path):
    with requests.get(target_url, stream=True) as response:
        with open(filepath, 'wb') as file:
            for chunk in response.iter_content(chunk_size=8192):
                file.write(chunk)

    # ダウンロードしたZIPファイルを解凍
    with zipfile.ZipFile(filepath, 'r') as zip_ref:
        zip_ref.extractall(dest_path)

    # ZIPファイルを削除
    os.remove(filepath)

class DownloadEdgeDriver(object):
    def __init__(self, url = 'https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/'):
        self.target_url = url

    def __analyse_edge_driver_version(self,html_content):
        dict_version_urllinkinfos = {}
        # BeautifulSoupを使用してHTMLを解析
        soup = BeautifulSoup(html_content, "html.parser")

        # バージョンの取得
        version = soup.select_one(".block-web-driver__versions strong").next_sibling.strip()

        # ダウンロード用URLの取得
        download_links = soup.select(".block-web-driver__version-links a")
        download_urls = {link.text.strip(): link['href'] for link in download_links}

        for platform, url in download_urls.items():
            dict_version_urllinkinfos[platform] = url
        return version, dict_version_urllinkinfos

    def __extract_edge_webdriver_list(self):
        # Microsoft Edge WebDriverのダウンロードページURL

        # ページのHTMLを取得
        response = requests.get(self.target_url)
        html_content = response.text

        # BeautifulSoupを使用してHTMLを解析
        soup = BeautifulSoup(html_content, "html.parser")

        # WebDriverのバージョン一覧を取得
        version_dl_list = []
        for option in soup.select(".block-web-driver__versions"):
            #version_info = option.text.strip()
            version, dict_urllinkinfos = self.__analyse_edge_driver_version( str(option) )
            dict_iteminfo = {}
            dict_iteminfo["version"] = version
            dict_iteminfo["url_link"] = dict_urllinkinfos
            version_dl_list.append(dict_iteminfo)#[ version ] = dict_urllinkinfos

        return version_dl_list
    def download_Stable_version(self, platform = 'x64', dest_path = '/opt'):
        version_dl_list = self.__extract_edge_webdriver_list()
        dict_dl_info = version_dl_list[0]
        version = dict_dl_info["version"]
        #Linux, Mac, Mac M1, x64, x86,ARM64
        dl_urllink = dict_dl_info["url_link"][platform]

        try:
            driver_file_name = 'edgedriver.zip'
            download_path = f'{dest_path}/{driver_file_name}'  # chromedriver_path.with_name("chromedriver.zip")

            # ChromeDriverをダウンロード
            #with requests.get(chromedriver_url, stream=True) as response:
            download_file( dl_urllink, download_path, dest_path  )
        except Exception as e:
            print(e)

    def download(self, version, platform='x64', dest_path='/opt'):
        version_dl_list = self.__extract_edge_webdriver_list()
        dict_dl_info = [ item  if item["version"] == version else None for item in version_dl_list ]
        version = dict_dl_info["version"]
        # Linux, Mac, Mac M1, x64, x86,ARM64
        dl_urllink = dict_dl_info["url_link"][platform]

        try:
            driver_file_name = 'edgedriver.zip'
            download_path = f'{dest_path}/{driver_file_name}'  # chromedriver_path.with_name("chromedriver.zip")

            # ChromeDriverをダウンロード
            # with requests.get(chromedriver_url, stream=True) as response:
            download_file(dl_urllink, download_path, dest_path)
        except Exception as e:
            print(e)

#download eg_webdriver
platform = 'x64'
dest_path = '/temp'
DownloadEdgeDriver().download_Stable_version(platform, dest_path )

## 補足
Windows上で、次のテストコードを使用して動作を確認しました。

platform = 'x64'
dest_path = '/temp'
DownloadEdgeDriver().download_Stable_version(platform, dest_path )

その結果、C:\tempのディレクトリにmsedgedriver.exeファイルがダウンロードされました。

11
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
8