LoginSignup
0
3

More than 3 years have passed since last update.

python+seleniumでchromeの操作を自動化

Last updated at Posted at 2020-05-22

概要

Seleniumを用いた自動テストやWebクローラーを実現する。
Seleniumはいくつかの言語・ブラウザでサポートされているが、今回はPythonとChromeを使う。

Seleniumがプラットフォームとなって、各ブラウザの共通のインターフェースを提供している。WebDriver(ChromeならChromeDriver)を使って、ブラウザを操作することができる。

Google Chromeのインストール

標準ではリポジトリが無いので追加。

$ sudo vim /etc/yum.repos.d/google-chrome.repo
google-chrome.repo
[google-chrome]
name=google-chrome
baseurl=http://dl.google.com/linux/chrome/rpm/stable/$basearch
enabled=1
gpgcheck=1
gpgkey=https://dl-ssl.google.com/linux/linux_signing_key.pub

安定版のChromeをインストール


$ sudo yum update
$ sudo yum install google-chrome-stable

バージョンを確認しておく(WebDriverと合わせる必要があるため:今回はversion 83)

$ google-chrome-stable --version
Google Chrome 83.0.4103.61

これでブラウザは準備完了。

ChromeDriverをインストール

ブラウザとバージョンを一致させる。

$ wget https://chromedriver.storage.googleapis.com/83.0.4103.39/chromedriver_linux64.zip
$ unzip chromedriver_linux64.zip
$ chmod 755 chromedriver
$ mv chromedriver /usr/local/bin/
$ chromedriver --version
ChromeDriver 83.0.4103.39 (.....................)

Pythonと、今回使うライブラリをインストール

$ sudo yum install python3
$ python3 -m pip install selenium chromedriver-binary

Pythonと、Selenium、ChromeDriverのライブラリがインストールできたので、実装開始。

selenium-test.py
from selenium import webdriver

driver = webdriver.Chrome()
# 色々操作
driver.quit()

実行する

$ python3 ./selenium-test.py

ブラウザが開いて自動操作されているのが確認できる。

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3