selenium 元素等待条件


<html>
<head>
    <title>

    title>
head>
<body>
<script>
    function f() {
        window.setTimeout("populate()", 2000);
    }
    function populate() {
        document.f1.t1.value = "populated";
        document.getElementById("id1").innerHTML = "
id 2
" } 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 os

from 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()