Python で Selenium を使ってみる
前準備
Python のインストールと必要なPythonライブラリのインストール(Windows上)
- Python のインストール
注:既にPython(バージョン3.12を推奨)がインストール済みの場合は,この手順は不要である.
winget(Windowsパッケージマネージャー)を使用してインストールを行う
- Windowsで,コマンドプロンプトを管理者権限で起動する(手順:Windowsキーまたはスタートメニュー,「cmd」と入力,右クリックメニューなどで「管理者として実行」を選択)
- winget(Windowsパッケージマネージャー)が利用可能か確認する:
winget --version
- Pythonのインストール(下のコマンドにより Python 3.12 がインストールされる).
reg add "HKLM\SYSTEM\CurrentControlSet\Control\FileSystem" /v LongPathsEnabled /t REG_DWORD /d 1 /f REM Python をシステム領域にインストール winget install --scope machine --id Python.Python.3.12 --id Python.Launcher -e --silent REM Python のパス set "INSTALL_PATH=C:\Program Files\Python312" echo %PATH% | find /i "%INSTALL_PATH%" >nul if errorlevel 1 setx PATH "%PATH%;%INSTALL_PATH%" /M >nul echo %PATH% | find /i "%INSTALL_PATH%\Scripts" >nul if errorlevel 1 setx PATH "%PATH%;%INSTALL_PATH%\Scripts" /M >nul
- 必要なPythonライブラリのインストール
【関連する外部ページ】
【サイト内の関連ページ】
Selenium WebDriver の Python クライアント・ドライバのインストール
- Selenium WebDriver のダウンロード Web ページを開く
- Python の横の「Download」をクリック
(オプション) Google Chrome で Scraper 拡張機能をインストール https://chrome.google.com/webstore/detail/scraper/mbigbapnjcgaffohmbkdlecaccepngjd
分析したいウエブページを 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
https://addons.mozilla.org/ja/firefox/addon/skip-addon-check/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)