一、expected_conditions
之前在 selenium之python源码解读-WebDriverWait 中说到,until方法中method参数,需要传入一个function对象,如果每次都自定义或者使用lambda函数,显得比较麻烦。
其实在expected_conditions中,Selenium提供了一些常用的元素查找的条件类
在seleniumwebdriversupportexpected_conditions.py中定义的所有类如下:
class title_contains(object): class presence_of_element_located(object): class visibility_of_element_located(object): class visibility_of(object): class presence_of_all_elements_located(object): class visibility_of_any_elements_located(object): class visibility_of_all_elements_located(object): class text_to_be_present_in_element(object): class text_to_be_present_in_element_value(object): class frame_to_be_available_and_switch_to_it(object): class invisibility_of_element_located(object): class element_to_be_clickable(object): class staleness_of(object): class element_to_be_selected(object): class element_located_to_be_selected(object): class element_selection_state_to_be(object): class element_located_selection_state_to_be(object): class number_of_windows_to_be(object): class new_window_is_opened(object): class alert_is_present(object):
在上面定义的类中都实现了 __call__(self, driver)方法,这就意味着该类的对象是一个可调用的对象
如以visibility_of_element_located类为例:
实例化一个对象:visibility_of_element_located(locator)
在对象后加():调用对象,即调用类的 __call__方法,visibility_of_element_located(locator)(driver)
二、类中的 __init__ 和__call__方法传参总结
1、传入locator,和driver参数
def __init__(self, locator): self.locator = locator def __call__(self, driver): return _find_element(driver, self.locator)
而locator,需要传入一个iterateble对象,如tuple,(by.ID,"id")
def _find_element(driver, by): """Looks up an element. Logs and re-raises ``WebDriverException`` if thrown.""" try: return driver.find_element(*by) except NoSuchElementException as e: raise e except WebDriverException as e: raise e
2、传入element,和ignored参数
def __init__(self, element): self.element = element def __call__(self, ignored): return _element_if_visible(self.element)
该类型的传参有4个
class visibility_of(object) class staleness_of(object) class element_located_to_be_selected(object) class element_selection_state_to_be(object)
lement_located_to_be_selected(object)和element_selection_state_to_be(object)实现的功能是一样的
3、其他还有title、window、handler、alert此处不再一一例举,具体查看源码