selenium 元素等待條件
阿新 • • 發佈:2022-03-08
<html> <head> <title> </title> </head> <body> <script> function f() { window.setTimeout("populate()", 2000); } function populate() { document.f1.t1.value = "populated"; document.getElementById("id1").innerHTML = "<div id ='id2'>id 2</div>" } </script> <form name="f1"> <input type="text" name="t1"> <input type="button" value="Click me" onclick="f()"> <div id="id1"> </div> </form> </body> </html>
等待時間為兩秒 如果等待時間改為1或者找不到元素則丟擲異常
from selenium import webdriver import osfrom selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait class Testcase(object): def __init__(self): self.driver = webdriver.Chrome() path = os.getcwd() file_path= os.path.join(path, "study06.html") self.driver.get(file_path) self.driver.maximize_window() def test01(self): self.driver.find_element_by_id('btn').click() wait = WebDriverWait(self.driver, 5) # text_to_be_present_in_element 判斷指定的元素中是否包含了預期的字串 wait.until(EC.text_to_be_present_in_element((By.ID, 'id2'), 'id 2')) print(self.driver.find_element_by_id("id2").text) print("ok") if __name__ == '__main__': case = Testcase() case.test01() case.driver.quit()