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

一、判断页面的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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值