LoginSignup
4
5

【Selenium】とりあえずこれだけあればOK? Python selenium

Last updated at Posted at 2023-02-25

はじめに

Seleniumって定期的に忘れますよね(?)
操作を一通りメモ書きしておきます。

とりあえずimportしておくもの

from selenium import webdriver # ブラウザ操作そのものに使用
from selenium.webdriver.common.by import By #要素を探す際に使用
from selenium.webdriver.chrome.options import Options #ブラウザを非表示状態で操作する際に使用
from webdriver_manager.chrome import ChromeDriverManager #入っているchromeと同じバージョンのドライバーをインストールするために使用

ブラウザを起動/終了する

# ブラウザを非表示で動かすための設定
options = Options()
options.add_argument("--headless") #コメントアウトでブラウザ表示

# 現在のブラウザに対応するドライバーをインストールしてブラウザを開く
browser = webdriver.Chrome(ChromeDriverManager().install(),options=options)

# ブラウザを閉じる
browser.quit()

URLを開く

# ブラウザでURLを開く
url = "https://www.google.com/"
browser.get(url)

要素のオブジェクトを取得

browser.find_element()またはbrowser.find_elements()を使用する。
引数は(by,value)
find_elementsの場合はリストが返ってくる。

xpathをchromeでコピーしてくると中身に"を含むので、xpath全体を'でくくる必要がある。

# idで取得
elem = browser.find_element(By.ID,"***")
# xpathで取得
elem = browser.find_element(By.XPATH,'***')
# htmlタグ名で取得
elems = browser.find_elements(By.TAG_NAME,'***')

要素に対する操作

# キー送信
elem.send_keys("***")
# クリック
elem.click()

要素から何かを取得

# テキスト取得
elem.text
# リンク先の取得
elem.get_attribute("href")
# htmlの取得
elem.get_attribute("outerHTML")

要素の調べ方

Chromeで目当てのサイトを開きF12でDevToolを起動すると要素のxpathやcss styleなどが取得できる。
image.png

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