Python で Selenium を使ってみる

前準備

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

  1. Python のインストール

    注:既にPython(バージョン3.12を推奨)がインストール済みの場合は,この手順は不要である.

    winget(Windowsパッケージマネージャー)を使用してインストールを行う

    1. Windowsで,コマンドプロンプト管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
    2. winget(Windowsパッケージマネージャー)が利用可能か確認する:
      winget --version
      
    3. Pythonのインストール(下のコマンドにより Python 3.12 がインストールされる).
      winget install --scope machine Python.Launcher
      winget install --scope machine Python.Python.3.12
      
  2. 必要な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/