判断title(title_is)

判断 title 

获取页面 title 的方法可以直接用 driver.title 获取到,然后也可以把获取到的结果用做断言。
本篇介绍另外一种方法去判断页面 title 是否与期望结果一种,用到上一篇判断元素(expected_conditions)提到的 expected_conditions 模块里的 title_is 和 title_contains 两种方法

源码分析

1.首先看下源码,如下
class title_is(object):
"""An expectation for checking the title of a page.title is the expected title, which must be an exact matchreturns True if the title matches, false otherwise."""
'''翻译:检查页面的 title 与期望值是都完全一致,如果完全一致,返回 Ture,否则返回 Flase'''
def __init__(self, title):
self.title = title
def __call__(self, driver):
return self.title == driver.title
2.注释翻译:检查页面的 title 与期望值是都完全一致,如果完全一致,返回True,否则返回 Flase
3.title_is()这个是一个 class 类型,里面有两个方法
4.__init__是初始化内容,参数是 title,必填项
5.__call__是把实例变成一个对象,参数是 driver,返回的是 self.title ==driver.title,布尔值

判断 title:title_is()

1.首先导入 expected_conditions 模块
2.由于这个模块名称比较长,所以为了后续的调用方便,重新命名为 EC 了(有点像数据库里面多表查询时候重命名)
3.打开博客首页后判断 title,返回结果是 True 或 False

判断title包含:title_contains

1.这个类跟上面那个类差不多,只是这个是部分匹配(类似于 xpath 里面的
contains 语法)
2.判断 title 包含'Silence&'字符串

参考源码;

# coding: utf-8
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Firefox()
driver.get("http://www.cnblogs.com/101718qiong/")
# 判断title完全等于
title = EC.title_is(u"Silence&QH - 博客园")
print title(driver)
# 判断title包含
title1 = EC.title_contains("Silence&QH")
print title1(driver)
# 另外写法
r1 = EC.title_is(u"Silence&QH - 博客园")(driver)
r2 = EC.title_contains("Silence&QH")(driver)
print r1
print r2

 

posted @ 2017-12-11 15:48  Silence&QH  阅读(1086)  评论(0编辑  收藏  举报