Pythonでブラウザを自動操作する話
PythonでSelenium Webdriverという、ブラウザ操作の自動化ソフトを動かしてみます。
環境
Windows10 64bit
Chocolatey
Python 3.7.4
Selenium Webdriverを動かすにあたって、2つの手順が必要です。
①Seleniumのインストール
②Webdriverの入手
①Seleniumのインストール
PyCharmのパッケージマネージャを使うと簡単にインストールをすることができます。
プロジェクトを用意し、seleniumのimport文を書くと、
画像のようにエラー表示がされるので、
吹き出し上の「Install package selenium」を選択するだけでインストールが完了します。
②Webdriverの入手
次に必要なのが、Webdriverの入手です。
今回は、Google Chrome用のWebdriverを入手していきます。
ここで一つ注意が必要なのは、
インストールされているGoogle Chromeのバージョンに応じたWebdriverを入手する必要がある
という点です。
異なるバージョン用のWebdriverを入れても動作せずエラーとなります。
Google Chromeのバージョンは
[ヘルプ] → [Google Chromeについて]
より確認することができます。
今回はChocolateyを利用してWebdriverを入手したいと思います。
Chocolateyでは現在、いくつかのChrome用Webdriverがインストールできます。
Chocolatey Gallery | Packages matching chromedriver
今回は、ダウンロード数も多く、バージョンアップも行われていそうな
Chocolatey Gallery | Selenium Chrome Driver 76.0.3809.68
をインストールします。
リンク先にもコマンドが記載されていますが、
choco install selenium-chrome-driver
でインストールすることが可能です。
実際にやってみます。
PS C:\WINDOWS\system32> choco install selenium-chrome-driver Chocolatey v0.10.15 2 validations performed. 1 success(es), 1 warning(s), and 0 error(s). Validation Warnings: - A pending system reboot request has been detected, however, this is being ignored due to the current Chocolatey configuration. If you want to halt when this occurs, then either set the global feature using: choco feature enable -name=exitOnRebootDetected or pass the option --exit-when-reboot-detected. Installing the following packages: selenium-chrome-driver By installing you accept licenses for the packages. Progress: Downloading selenium-chrome-driver 76.0.3809.68... 100% selenium-chrome-driver v76.0.3809.68 [Approved] selenium-chrome-driver package files install completed. Performing other installation steps. The package selenium-chrome-driver wants to run 'chocolateyInstall.ps1'. Note: If you don't run this script, the installation will fail. Note: To confirm automatically next time, use '-y' or consider: choco feature enable -n allowGlobalConfirmation Do you want to run the script?([Y]es/[A]ll - yes to all/[N]o/[P]rint): Y Downloading selenium-chrome-driver from 'https://chromedriver.storage.googleapis.com/76.0.3809.68/chromedriver_win32.zip' Progress: 100% - Completed download of C:\Users\hiyoriaya\AppData\Local\Temp\selenium-chrome-driver\76.0.3809.68\chromedriver_win32.zip (4.44 MB). Download of chromedriver_win32.zip (4.44 MB) completed. Hashes match. Extracting C:\Users\hiyoriaya\AppData\Local\Temp\selenium-chrome-driver\76.0.3809.68\chromedriver_win32.zip to C:\tools\selenium... C:\tools\selenium Added C:\ProgramData\chocolatey\bin\chromedriver.exe shim pointed to 'c:\tools\selenium\chromedriver.exe'. Environment Vars (like PATH) have changed. Close/reopen your shell to see the changes (or in powershell/cmd.exe just type `refreshenv`). The install of selenium-chrome-driver was successful. Software installed to 'C:\tools\selenium' Chocolatey installed 1/1 packages. See the log for details (C:\ProgramData\chocolatey\logs\chocolatey.log). PS C:\WINDOWS\system32>
ChocolateyにてWebdriverを導入することで、Chromeのバージョンが上がった際にも
choco upgrade selenium-chrome-driver
とすると最新版に更新できるという点が便利です。
Selenium Webdriverの動作確認
では早速動作確認をしてみましょう。
import time import os from selenium import webdriver driver = webdriver.Chrome() # スクリーンショットの保存先を指定 fileName = os.path.join(os.path.dirname(os.path.abspath(__file__)), "screenshot.png") # 指定したURLを開く driver.get('https://iine-programming.hatenablog.com/') time.sleep(5) # スクリーンショットを撮影 driver.save_screenshot(fileName) # Webdriverの終了 driver.quit()
うまくSeleniumを使う準備ができていれば、
このコードを実行するとChromeが立ち上がり、このブログにアクセスをするはずです。
また、Seleniumではスクリーンショットを撮影することもできます。
上記のコードでは実行ファイルの階層に screenshot.png という形式で保存をしています。