前言
獲取頁面title的方法可以直接用driver.title獲取到,然后也可以把獲取到的結果用做斷言。
本篇介紹另外一種方法去判斷頁面title是否與期望結果一種,用到上一篇Selenium2+python自動化42-判斷元素(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 match
returns 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包含'上海-悠悠'字符串
四、參考代碼
# 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/yoyoketang")
# 判斷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
學習過程中有遇到疑問的,可以加selenium(python+java) QQ群交流:646645429
另外成立了python接口自動化QQ群:226296743
selenium+python高級教程》已出書:selenium webdriver基於Python源碼案例
(購買此書送對應PDF版本)