上一篇介紹selenium中一個模塊expected_conditions的title_is和title_contains方法。
title_is:判斷當前頁面的title是否完全等於(==)預期字符串,返回是布爾值 title_contains 判斷當前頁面的title是否包含預期字符串,返回布爾值 |
這裏繼續舉例判斷文本是否存在的方法text_to_be_present_in_element,比如判定進入某個頁面後判定元素中是否存在指定的文本,當然結合騰訊企業郵箱的使用。
判斷文本text_to_be_present_in_element
查看源碼如下:
class text_to_be_present_in_element(object):
""" An expectation for checking if the given text is present in the
specified element.
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
locator,text兩個參數,分別是定位器和文本,檢查指定的元素中是否存在相應的文本。
判定郵箱是否登陸成功
郵箱登陸成功後,會顯示當前登陸賬戶的姓名或暱稱,那麼就可以登陸成功後判斷是否存在該姓名。
Locator參數的實參爲“ID"和"useralias",text參數的爲姓名。
可以看到返回的結果爲True。
# -*- coding: UTF-8 -*-
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Firefox()
driver.implicitly_wait(20)
user = "[email protected]"
pwd = "123456"
# 打開騰訊企業郵箱
driver.get("https://exmail.qq.com/login")
# 點擊 賬號密碼登陸
driver.find_element_by_class_name("js_show_pwd_panel").click()
# 輸入 賬戶
driver.find_element_by_id("inputuin").send_keys(user)
# 輸入 密碼
driver.find_element_by_id("pp").send_keys(pwd)
# 點擊 登錄
driver.find_element_by_id('btlogin').click()
loc = ("id","useralias")
text = "xxx"
emailtext = EC.text_to_be_present_in_element(loc,text)(driver)
print(emailtext)
if emailtext:
print("登陸成功!")
else:
print("登陸失敗")