LoginSignup
1
0

More than 5 years have passed since last update.

社内向け学習(その他 001)

Last updated at Posted at 2018-04-22

社内向け学習(その他 001)

自動テストとヘッドレスブラウザ(画面なしブラウザ)


最近はchromeのヘッドレスモードが標準で使えるということなので、

少し弄ってみることにしました。


seleniumしてみます。

selenium.py
# ブラウザを開く。
driver = webdriver.Chrome()

# Googleの検索TOP画面を開く。
driver.get("https://www.google.co.jp/")

# 検索語として「selenium」と入力し、Enterキーを押す。
driver.find_element_by_id("lst-ib").send_keys("selenium")
driver.find_element_by_id("lst-ib").send_keys(Keys.ENTER)

# タイトルに「Selenium - Web Browser Automation」と一致するリンクをクリックする。
driver.find_element_by_link_text("Selenium - Web Browser Automation").click()

# ブラウザを終了する。
driver.close()
chrome_headless.py

# ヘッドレスモードを有効にする
options = Options()
options.add_argument('--headless')
options.add_argument('--disable-gpu')
options.add_argument('--no-sandbox')
# ChromeのWebDriverオブジェクトを作成する。
driver = webdriver.Chrome(chrome_options=options)

# Googleのトップ画面を開く。
driver.get('https://www.google.co.jp/')

# 検索語として「selenium」と入力し、Enterキーを押す。
driver.find_element_by_id("lst-ib").send_keys("selenium")
driver.find_element_by_id("lst-ib").send_keys(Keys.ENTER)
# タイトルに「Selenium - Web Browser Automation」と一致するリンクをクリックする。
# なぜか触れないのでスクロール。
# driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
driver.find_element_by_link_text("Selenium - Web Browser Automation").click()

# 証拠のスクリーンショットを撮る。
driver.save_screenshot('search_results_ebi.png')

# スクレイピング
elm = driver.find_element_by_xpath('//*[@id="mainContent"]/p[1]')
print(elm.text)

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

所感

私がPhantomJSなどのヘッドレスブラウザを使ったことがないので単純に比較はできないのですが、おもったよりも使いやすい印象を受けました。

良いところ。

  1. 自動実行できるように準備しておけば1台の端末でテストを動かしながら、
    作業が継続できる。(当初の目的)
  2. 少し処理が早い。(気がする)

気をつけること。

  1. 画面を見ながらじゃないので、画面の挙動でおかしい箇所がよくわからない。 (なれれば大丈夫かと。)

みんなもいじってみましょう。

1
0
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
1
0