Python_页面等待的简单封装(WebDriverWait)

页面等待的封装(WebDriverWait)

 

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
import  traceback
from selenium.common.exceptions import TimeoutException

class WaitUtil(object):

    def __init__(self,driver):
        self.driver = driver
        self.wait =  WebDriverWait(self.driver,5)
        self.locate_method = {"id":By.ID,
                             "name":By.NAME,
                              "link_text":By.LINK_TEXT,
                              "partial_link_text":By.PARTIAL_LINK_TEXT,
                              "xpath":By.XPATH
                              }


    def presenceOfElement(self,locate_method,locate_expression):
        try:
            element = self.wait.until \
                (lambda x: x.find_element(self.locate_method[locate_method]
            ,locate_expression))
            return element
        except TimeoutException:
            traceback.print_exc()
            raise TimeoutException


if __name__ == "__main__":
    driver = webdriver.Firefox(executable_path="d:\\geckodriver")
    wait_object = WaitUtil(driver)
    driver.get("http://www.baidu.com")
    try:
        element = wait_object.presenceOfElement("id","kw")
        element.send_keys("光荣之路")
        import time
        time.sleep(3)
    except TimeoutException:
        print("元素未定位!")
posted @ 2019-12-31 01:10  翻滚的小强  阅读(853)  评论(0)    收藏  举报