判断元素是否存在页面的两种不同写法

直接上代码

#coding:utf-8
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

driver = webdriver.Chrome()
driver.get("http://www.baidu.com")

def find_element(locator,timeout=10):
    '''定位方法封装成函数'''
    #lambda判断元素是否存在
    # element = WebDriverWait(driver, timeout,1).until(lambda x : x.find_element(*locator))
    
    #presence_of_element_located判断元素是否存在
    try:
        element = WebDriverWait(driver, timeout,1).until(EC.presence_of_element_located(locator))
    except TimeoutException:
        print("元素没有定位到%s" % str(locator))
    else:
        return element

try:
    input_loc = ("id","kw1")
    button_loc = ("id","su")
    find_element(input_loc).send_keys("yoyo")
    find_element(button_loc).click()
    time.sleep(3)
finally:
    driver.quit()
posted @ 2018-10-08 17:48  悠然现南山  阅读(475)  评论(0编辑  收藏  举报