1-Selenium - expected_conditions

about expected_conditions

expected_conditions预期条件,封装了各种场景判断,比如说判断某个元素是否可见,是否存在,常搭配等待或者在断言中使用。

常用方法

方法 描述 备注
EC.element_to_be_clickable 判断一个元素是否可以点击

EC.title_contains/EC.title_is

这两个方法都是用来判断title的,区别是:

  • EC.title_contains只要包含即可
  • EC.title_is必须完全匹配
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()

driver.get('https://www.baidu.com')

# title中包含即可
print(EC.title_contains("百度")(driver))  # True
print(EC.title_contains("必应")(driver))  # False

# title完全匹配
print(EC.title_is("百度一下")(driver))  # False
print(EC.title_is("百度一下,你就知道")(driver))  # True

driver.quit()

EC.visibility_of_element_located/EC.presence_of_element_located

这俩都是判断元素是否存在,但是区别还是有的:

  • EC.visibility_of_element_located,我们需要找到元素,并且该元素也可见。
  • EC.presence_of_element_located,我们不关心元素是否可见,只关心元素是否存在在页面中。

推荐使用EC.visibility_of_element_located

from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait


driver = webdriver.Chrome()
wait = WebDriverWait(driver, timeout=3)

driver.get('https://www.baidu.com')

try:
    # id:su 存在,不报错
    wait.until(EC.visibility_of_element_located((By.ID, 'su')), "No search element")
except Exception as e:
    print(1111111, e)
try:
    # id: sux 不存在,报错
    wait.until(EC.presence_of_element_located((By.ID, 'sux')), "No search element")
except BaseException as e:
    print(2222222, e)  # 2222222 Message: No search element
driver.quit()

EC.element_to_be_clickable

在该网站,每当输入值并点击确认后,input框会有一个短暂的disabled的状态,即不可选中,但该元素还存在,只是无法选中,也就无法输入值,所以,在反复往该input中输入值的时候,要提前判断该元素是否是可以点击,这里用了EC.element_to_be_clickable来判断元素是否可点击,具体示例如下:

import time
import random
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By

driver = webdriver.Firefox()
wait = WebDriverWait(driver=driver, timeout=10)
try:
    driver.get("https://www.cs.usfca.edu/~galles/visualization/BTree.html")
    for i in random.sample(range(500), 50):
        wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="AlgorithmSpecificControls"]/td[1]/input'))).send_keys(i)
        wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="AlgorithmSpecificControls"]/td[2]/input'))).click()
        time.sleep(2)
except Exception as e:
    print(e)
finally:
    time.sleep(60)
    driver.quit()

see also:

Selenium2+python自动化43-判断title(title_is)
1128UI自动化测试经验分享-显式等待(二)expected_conditions模块、visibility_of_element_located(locator)
presence_of_element_located与visibility_of_element_located区别
Selenium笔记(7)常见的坑

posted @ 2020-04-08 15:22  听雨危楼  阅读(936)  评论(0编辑  收藏  举报