python3+selenium自动化测试-如何断言20

2020-09-07  本文已影响0人  C1R2

一、判断页面的title
其中expected_conditions模块,提供了title_is和title_contains两种方法
实例1:
1.首先导入expected_conditions模块,并重命名EC方便以后调用
from selenium.webdriver.support import expected_conditions as EC
2.打开百度,利用EC.title_is(u'百度一下,你就知道'),断言返回结果是True或False

代码参考1:

# coding:utf-8
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
driver.get("https://www.baidu.com")

print(driver.title)
# 判断title完全等于
title = EC.title_is(u'百度一下,你就知道')
print(title(driver))

# 判断title包含,只是这个是部分匹配
title1 = EC.title_contains(u'百度一下')
print(title1(driver))

# 另外一种写法,交流QQ群:232607095
r1 = EC.title_is(u'百度一下,你就知道')(driver)
r2 = EC.title_contains(u'百度一下')(driver)
print(r1)
print(r2)

二、判断弹出框存在alert_is_present
其中expected_conditions模块,提供了alert_is_present
实例2
1.没找到就返回False;找到就返回alert对象

# 百度-设置弹框页面,点保存按钮
js = 'document.getElementsByClassName("prefpanelgo")[0].click();'
driver.execute_script(js)
# 判断弹窗结果 
result = EC.alert_is_present()(driver)
if result:
    print result.text
    result.accept()
else:
    print "alert 未弹出!"

三、判断文本text_to_be_present_in_element
其中expected_conditions模块,提供了text_to_be_present_in_element
提供了text_to_be_present_in_element_value判断元素的value值
源码分析
class text_to_be_present_in_element(object):
""" An expectation for checking if the given text is present in the
specified element.
locator, text
"""

    '''翻译:判断元素中是否存在指定的文本,参数:locator, text'''
    def __init__(self, locator, text_):
        self.locator = locator
        self.text = text_

    def __call__(self, driver):
        try:
            element_text = _find_element(driver, self.locator).text
            return self.text in element_text
        except StaleElementReferenceException:
            return False
1.翻译:判断元素中是否存在指定的文本,两个参数:locator, text
2.__call__里返回的是布尔值:Ture和False

代码参考2:

# coding:utf-8
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
url = "https://www.baidu.com"
driver.get(url)

locator = ('class name', 'mnav')
text = u"新闻"
result = EC.text_to_be_present_in_element(locator, text)(driver)
print(result)

# 下面是失败的案例
text1 = u"新闻告诉"
result1 = EC.text_to_be_present_in_element(locator, text1)(driver)
print(result1)

locator2 = ("id", "su")
text2 = u"百度一下"
result2 = EC.text_to_be_present_in_element_value(locator2, text2)(driver)
print(result2)

参考链接
https://www.cnblogs.com/yoyoketang/p/6539117.html
https://www.cnblogs.com/yoyoketang/p/6569170.html
https://www.cnblogs.com/yoyoketang/p/6577005.html

上一篇下一篇

猜你喜欢

热点阅读