Python で Selenium を使ってみる

前準備

Python のインストールと必要なPythonライブラリのインストール(Windows上)

  1. Python 3.12 のインストール

    インストール済みの場合は実行不要。

    管理者権限でコマンドプロンプトを起動(手順:Windowsキーまたはスタートメニュー > cmd と入力 > 右クリック > 「管理者として実行」)し、以下を実行する。管理者権限は、wingetの--scope machineオプションでシステム全体にソフトウェアをインストールするために必要である。

    REM Python をシステム領域にインストール
    winget install --scope machine --id Python.Python.3.12 -e --silent
    REM Python のパス設定
    set "PYTHON_PATH=C:\Program Files\Python312"
    set "PYTHON_SCRIPTS_PATH=C:\Program Files\Python312\Scripts"
    echo "%PATH%" | find /i "%PYTHON_PATH%" >nul
    if errorlevel 1 setx PATH "%PATH%;%PYTHON_PATH%" /M >nul
    echo "%PATH%" | find /i "%PYTHON_SCRIPTS_PATH%" >nul
    if errorlevel 1 setx PATH "%PATH%;%PYTHON_SCRIPTS_PATH%" /M >nul

    関連する外部ページ

    Python の公式ページ: https://www.python.org/

  2. AI エディタ Windsurf のインストール

    Pythonプログラムの編集・実行には、AI エディタの利用を推奨する。ここでは,Windsurfのインストールを説明する。

    管理者権限でコマンドプロンプトを起動(手順:Windowsキーまたはスタートメニュー > cmd と入力 > 右クリック > 「管理者として実行」)し、以下を実行して、Windsurfをシステム全体にインストールする。管理者権限は、wingetの--scope machineオプションでシステム全体にソフトウェアをインストールするために必要となる。

    winget install --scope machine Codeium.Windsurf -e --silent

    関連する外部ページ

    Windsurf の公式ページ: https://windsurf.com/

  3. 必要なPythonライブラリのインストール
    1. Windowsで,管理者権限コマンドプロンプトを起動(手順:Windowsキーまたはスタートメニュー > cmd と入力 > 右クリック > 「管理者として実行」)。
    2. 以下のコマンドを実行し,必要なライブラリをインストールする.
      pip install -U selenium
      

【関連する外部ページ】

【サイト内の関連ページ】

Selenium WebDriver の Python クライアント・ドライバのインストール

  1. Selenium WebDriver のダウンロード Web ページを開く

    http://docs.seleniumhq.org/download

  2. Python の横の「Download」をクリック

    (オプション) Google Chrome で Scraper 拡張機能をインストール https://chrome.google.com/webstore/detail/scraper/mbigbapnjcgaffohmbkdlecaccepngjd

    Scraper のボタンが増えるので確認

    分析したいウエブページを Google Chrome ウエブブラウザで表示 例えば https://store.nintendo.co.jp/customize.html その状態で,Google Chrome でディベロッパーツールを起動 Ctrl+Shift+I 左上の 「Select an element in the page to inspect it」 のアイコンをクリック HTML 画面内で要素を選ぶ 右側の画面で,右クリックメニューで,「Copy XPath」 //*[@id="custoize_toCart"]/span/button

    from selenium import webdriver
    from selenium.webdriver.support.ui import Select
    import time
    
    browser = webdriver.Chrome()
    browser.get('https://store.nintendo.co.jp/customize.html')
    while True:
        try:
            a = browser.find_element_by_xpath('//*[@id="custoize_toCart"]/span/button')
            break
        except:
            print("busy")
            time.sleep(1)
    try:
        a.click()
    except:
        print("fail")
    print(a)
    
    https://addons.mozilla.org/ja/firefox/addon/skip-addon-check/