0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

seleniumをとりあえずちゃちゃっと動かしてみたい[mac向け]

0
Last updated at Posted at 2020-09-10

はじめに

seleniumっていうwebブラウザのテストツール、
ざっくり言えばちょっとコードを書けばweb画面を自動操作できてしまうというものがあると知って
とりあえず試したかった。

先人の知恵を大いに借りたが、ところどころ躓きポイントがあったのでメモ。

写経に近いものになってしまうが、基本は
たった3行のpythonで始めるSelenium入門
に沿い、躓いたところを記録として残しておく。(2020.9.10時点)

できること

seleniumを使ってブラウザ画面で
「たぬき 画像」という文字列の検索結果を自動で表示させる

環境

  • Mac
  • python3.8
  • Chrome

事前準備

  • homebrewをインストール
  • pythonをインストール

※ 上記は参考記事に記載あり。

手順

  • chromedriverのインストール
$ brew install chromedriver

# 上記でインストールできなかったので、エラー文のとおりこちらを試したらいけた
$ brew cask install chromedriver
  • seleniumをインストール
$ pip install selenium
  • test.pyを作成し、下記を記述する
test.py
from selenium import webdriver

driver = webdriver.Chrome("chromedriverのパス") 

driver.get("https://google.co.jp")

chromedriverのパスは、which chromedriverで調べられる

  • test.pyを実行する
$ python test.py

ここでポップアップでエラーが出たので、下記を参考にダウンロードしたアプリケーションの実行許可をした。

seleniumを使用しようとしたら、「"chromedriver"は開発元を検証できないため開けません。」と言われた

これでchromeのwebブラウザが開けるはず。

ここまでうまくできたら、下記を記述する

test.py
from selenium import webdriver 
from selenium.webdriver.common.keys import Keys # 追加

driver = webdriver.Chrome("/usr/local/bin/chromedriver")
driver.get("https://google.co.jp")

text = driver.find_element_by_name("q") # 検索ボックスのname属性を指定
text.send_keys("たぬき 画像")# 文字列"たぬき 画像"をテキストボックスに入力
text.send_keys(Keys.ENTER) # ENTERを押下する特殊キーを使う

躓きポイント

  • 検索ボックスのid属性が見つけられなかった

  →name属性を指定することにした

  • click()を使うと、test.pyの実行時に後述のエラーが出た

  → (検索ボタンを探してクリックするのではなく、)ENTERを押下する設定にした1

エラー内容

 :
selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable

まとめ

なぜこのようなエラーが出るのかまでは調査できなかったが、
ひとまず、自動でwebブラウザが開き、勝手に検索ボックスに文字が入力され
検索結果が表示されるところまでたどり着くことができた。

  1. seleniumクイックリファレンスより

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?