LoginSignup
0
4

More than 1 year has passed since last update.

[Python]Selenium概要およびインストール、基本操作方法 メモ

Last updated at Posted at 2021-06-05
  • Windows環境でのPython + Selenium + Google Chrome利用方法や基本操作()についての備忘録記事。

Seleniumとは

  • Webブラウザ操作を自動化するためのフレームワーク。
  • WebDriverと呼ばれるAPI群とプロトコルを利用してWebブラウザ操作を行う。
  • 次の用途で利用される。
    • Webアプリケーションの UI テスト
    • Webブラウザ操作タスクの自動化
    • Webサイトのクローリングなど
  • サポート言語
    • Java
    • Python
    • C#
    • Ruby
    • JS
    • Kotlin など

事前準備

※Windows環境での例

1.Seleniumインストール

   pip install selenium

2.Google Chrome Webドライバーダウンロード

  • こちらのサイトから自環境で利用しているGoogle Chromeと同一バージョンのドライバーをダウンロードする。
  • Zipファイルを解凍し、コードから参照できる場所にchromedriver.exeを配置する。

サンプルコード

  • selenium」をGoogle検索するコード(公式参考)
  from selenium import webdriver
  from selenium.webdriver.common.by import By
  from selenium.webdriver.common.keys import Keys
  from selenium.webdriver.support.ui import WebDriverWait
  from selenium.webdriver.support.expected_conditions import presence_of_element_located
  # Google Chromeを操作するためのWebドライバを読み込む
  with webdriver.Chrome("./chromedriver.exe") as driver:
      # 任意のHTMLの要素が特定の状態になるまで待機するための設定
      wait = WebDriverWait(driver, 10)
      # Googleにアクセス
      driver.get("https://google.com")
      # "selenium"で検索
      driver.find_element(By.NAME, "q").send_keys("selenium" + Keys.RETURN)
      # 1件目の検索結果を取得(描画されるまで待機)
      first_result = wait.until(
          presence_of_element_located((By.CSS_SELECTOR, "h3")))
      print(first_result.get_attribute("textContent"))

参考情報

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