For the selenium native lookup element method to encapsulate, in the timeout period within the specified time loop to find an element on the page
The benefits of this encapsulation:
1. Can effectively improve the search element of the small Lu, to avoid the element has not been loaded on the throw exception
2. Save time relative to Time.sleep and implictly_wait
3. Greatly reduce duplication of code, make use case writing more concise
Code:
#coding: Utf-8
#封装元素方法
From selenium import Webdriver
From Selenium.webdriver.support.ui import webdriverwait
From selenium.common.exceptions Import *
Import time
Class Base ():
def __init__ (self,driver):
Self.driver=driver
#查找元素
def find_element (self,locator): #locator参数是定位方式, such as ("id", "kw"), combine two parameters into one, * number is the two parameters to separate the value
Element=webdriverwait (self.driver,20,0.5). Until (Lambda x:x.find_element (*locator))
return element
#判断元素是否存在
def is_exists (Self,locator):
Try
Webdriverwait (self.driver,20,0.5). Until (Lambda x:x.find_element (*locator))
Return True
Except
Return False
#判断元素是否已经不存在, there is no return true, there is a return false
def element_is_disappeared (self,locator,timeout=30):
Is_disappeared=webdriverwait (self.driver,timeout,1, (elementnotvisibleexception)). Until_not (Lambda X:x.find_ Element (*locator). is_displayed ())
Print is_disappeared
#封装一个send_keys
def send_keys (Self,locator,text):
Self.find_element (Locator). Send_keys (text)
#封装一个click
def click (self,locator):
Self.find_element (Locator). Click ()
#运行主函数
If __name__== ' __main__ ':
Driver=webdriver. Chrome ()
Driver.get ("https://www.baidu.com")
#实例化
Base=base (Driver)
#定位输入框
input_loc= ("id", "kw")
#通过实例调用find_element来发送
Base.send_keys (Input_loc, "Selenium")
#点击按钮
button_loc= ("id", "su")
Base.click (Button_loc)
Time.sleep (3)
Driver.quit ()
* Method can be written according to the actual situation
Finding element methods using the Webdriverwait encapsulation