【Selenium + Python】要素があるかの判別方法

SeleniumPython を使って、クラス名が、「test」 というアンカーの要素があるかを判別したい時がありました。

以下の方法が考えられます。

方法その1

eles = driver.find_elements_by_class_name("test")
if len(eles) > 0:
ele = eles[0]
href = ele.get_attribute("href")

elements を使うと指定の要素がない場合、「[]」ゼロ配列で返します。

あとは、要素を探すタイムアウトの設定ができればいいんだけど。

方法その2

from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException

try:
WebDriverWait(driver, 0.1).until(
EC.presence_of_element_located*1
)
test = driver.find_element_by_class_name("test")
href = test.get_attribute("href")
except TimeoutException as ex:
print("TimeoutException")

この方法だとタイムアウトの時間を設定できるけど、設定した以上に時間がかかっている気がする。

でも、「方法その2」の方がまだ待ち時間が短いかもしれない。

*1:By.CLASS_NAME, "test"

返信を残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

CAPTCHA