【Python】Selenium を使ってスクレイピング

Uncategorized
427 words

私は結構な頻度でPCを初期化するんですが、その都度前使っていたツールをインストールしなおして使える状態までもっていっています。

でも毎回忘れちゃってて、都度検索しては「あぁじゃない、こうじゃない」ってやってるので、次忘れたときのために備忘録しておきます。

はじめに

  • Windows 10 Home 21H1
  • Python 3.8.10
  • Visual Studio Code 1.58.2
  • Selenium 3.141.0

Seleniumのインストール

下記コマンドを実行する。

1
pip install selenium

Successfully と表示されれば成功。ワーニングは気にしない。

WebDriverのインストール

今回はChromeを使ってスクレイピングしたいので、Chrome用のWebDriverをインストールします。

Seleniumを使うにはWebDriverが必須です。

こちらのサイトから最新のWebDriverをダウンロードします。

ダウンロードが出来たら適当なところに展開しておきます。

動作確認

とりあえず簡単なコードで動作確認します。

1
2
3
4
5
6
7
from selenium import webdriver
driver = webdriver.Chrome(executable_path="D:\Python\chromedriver_win32\chromedriver.exe")

driver.get("https://www.google.com/")

driver.close()
driver.quit()

Pythonで上記コードを実行して、正常に終了すればseleniumの導入は完了です。

エラーが出る場合は?

WebDriverException

Message: ‘chromedriver_win32’ executable may have wrong permissions. Please see https://sites.google.com/a/chromium.org/chromedriver/home

WebDriverのパスが正しくない可能性があります。よく確認してみて下さい。

Windowsの場合はファイル名まで正しく指定して下さい。

1
driver = webdriver.Chrome(executable_path="D:\Python\chromedriver_win32\chromedriver.exe")

SessionNotCreatedException

Message: session not created: This version of ChromeDriver only supports Chrome version 93
Current browser version is 92.0.4515.131 with binary path C:\Program Files\Google\Chrome\Application\chrome.exe

ChromeのバージョンとWebDriverのバージョンが一緒じゃない。一緒のバージョンを使いましょう。