LoginSignup
14
33

More than 3 years have passed since last update.

CentOS7でSelenium+Pythonを動かすまで

Last updated at Posted at 2019-04-07

Webアプリケーションテストツール Selenium 実行環境作成までの手順をまとめる。

前提環境

# cat /etc/redhat-release 
CentOS Linux release 7.4.1708 (Core)

ブラウザのインストール

Chromeの場合

  • Google Chrome用のyumリポジトリを作成
/etc/yum.repos.d/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
  • アップデート
yum update
  • 本体と日本語フォントをインストール
# yum -y install google-chrome-stable

# google-chrome --version
Google Chrome 73.0.3683.86

# yum -y install ipa-gothic-fonts ipa-mincho-fonts ipa-pgothic-fonts ipa-pmincho-fonts
  • GUIがないヘッドレスモードでHTMLを取得し、動作確認
google-chrome --headless --no-sandbox --dump-dom https://www.google.com/

Firefoxの場合

yum -y install firefox

Selenium導入

yum list installed | grep pythonpip -V で、Pythonパッケージ管理システム pip があるか確認する。
無ければ導入。

yum -y install python-pip
pip install --upgrade pip

pipからSelenium導入

pip install selenium

Webドライバ

ChromeDriverの場合

# pip install chromedriver-binary
# pip show chromedriver-binary
Version: 74.0.3729.6.0

# chromedriver-path
/usr/lib/python2.7/site-packages/chromedriver_binary
session not created: This version of ChromeDriver only supports Chrome version 74

とか

session not created: Chrome version must be between 70 and 73

のエラーが出た場合、Chrome のバージョンと ChromeDriver のバージョンが対応していないということ。
pip uninstall chromedriver-binary した上で、
http://chromedriver.chromium.org/downloads から対象バージョンを探して手動インストールしよう。

cd /usr/local/bin
wget https://chromedriver.storage.googleapis.com/73.0.3683.68/chromedriver_linux64.zip
unzip chromedriver_linux64.zip
chmod 755 chromedriver
rm chromedriver_linux64.zip 

GeckoDriver(Firefox)の場合

cd /usr/local/bin
wget https://github.com/mozilla/geckodriver/releases/download/v0.24.0/geckodriver-v0.24.0-linux64.tar.gz

実行時に selenium.common.exceptions.WebDriverException: Message: Unable to find a matching set of capabilities が出るときは、FirefoxとGeckoDriverのバージョンが合っていないときだから、双方のバージョンを最新にしてみよう。

動作確認

Python
from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
driver = webdriver.Chrome(options=options)

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

Firefoxの場合は、

from selenium.webdriver.firefox.options import Options

options = Options()
options.add_argument('-headless')
driver = webdriver.Firefox(options=options)

と書き替えればOK。

14
33
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
14
33