要素
記事
IT・テクノロジー
取得
最初
elem = driver.find_element(ロケータ, "対象")
全部
elem_list = driver.find_elements(ロケータ, "対象")
見つからなかったら [] を返す
ロケータ
XPath
from selenium.webdriver.common.by import By
By.XPATH
CSSセレクタ
from selenium.webdriver.common.by import By
By.CSS_SELECTOR
ID
from selenium.webdriver.common.by import By
By.ID
クラス
from selenium.webdriver.common.by import By
By.CLASS_NAME
name属性
from selenium.webdriver.common.by import By
By.NAME
<form>内の<input>に対して使う
タグ
from selenium.webdriver.common.by import By
By.TAG_NAME
リンクテキスト
部分一致
from selenium.webdriver.common.by import By
By.PARTIAL_LINK_TEXT
完全一致
from selenium.webdriver.common.by import By
By.LINK_TEXT
値
テキスト
elem.text
タグ名
elem.tag_name
属性
elem.get_attribute("属性")
HTML
elem.get_attribute("outerHTML")
サイズ
幅
elem.size["width"]
高さ
elem.size["height"]
位置
x
elem.location["x"]
y
elem.location["y"]
チェック
存在する
exists = bool(driver.find_elements(セレクタ, "対象"))
if exists:
表示されている
elem.is_displayed()
有効状態(グレーアウトされていない)
elem.is_enabled()
例外処理
from selenium.common.exceptions import NoSuchElementException
try:
elem = driver.find_element(セレクタ, "対象")
except NoSuchElementException as e:
print(e)