LoginSignup
91
92

More than 3 years have passed since last update.

【Python】SeleniumでHeadless Chromeを使おう

Last updated at Posted at 2018-04-27

目次

準備

  • selenium
  • Chrome(通常版)
  • Chrome Canary
  • Chrome driver

<追記>
Chrome(通常版)でもできますが,プログラムミスで簡単にChromeが起動しなくなるので,普段使いする人はCanaryを使うことをおすすめします。Chromeが起動しなくなった場合の対処法は最後に載せておきます。

selenium

pipでもcondaでもインストール可能です。

>> pip install selenium
>> conda install selenium

Chromedriver

pipまたはcondaで導入すれば,pythonパッケージと同様にバージョン管理ができるほか,import chromedriver_binaryでパスを通すことができるのでおすすめです。別の方法としては,brewでインストールすることもできます。

>> pip install chromedriver-binary
>> conda install python-chromedriver-binary
>> brew install chromedriver

コード例

Google検索画面のHTMLを取得し表示します。Chromedriverはpipまたはcondaでインストールしていることを想定しています。

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import chromedriver_binary

# ブラウザーを起動
options = Options()
options.binary_location = '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary'
options.add_argument('--headless')
driver = webdriver.Chrome(options=options)

# Google検索画面にアクセス
driver.get('https://www.google.co.jp/')

# htmlを取得・表示
html = driver.page_source
print(html)

# ブラウザーを終了
driver.quit()

Chromeオプション

headless以外にもChromeオプションはいろいろあるので,その中から私がよく使うものを紹介します。

  • headless:ヘッドレス指定
  • hide-scrollbars:スクロールバーを隠す
  • incognito:シークレットモード。拡張機能がオフになったり,履歴が残らなくなる。
  • window-size:ウィンドウサイズ指定

Chromeが開かなくなったときの対処法

一応,私が試した対処法を載せておきます。
PC再起動以外は,治ったり治んなかったりでした。

  • 起動しているChromeのタスクをすべて消去
  • 'headless'オプションを外してプログラム実行
  • PC再起動

その他のヘッドレスブラウザ

91
92
1

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
91
92