Python+Selenium练习(十八)-断言页面标题

练习场景:断言百度首页,获取title

一、

具体代码:

# coding=utf-8
import time
from selenium import webdriver

driver = webdriver.Chrome()
driver.maximize_window()
driver.get('https://www.baidu.com')
time.sleep(1)

# 方法一
try:
    assert u"百度一下" in driver.title
    print('Assertion test pass.')
except Exception as e:
    print('Assertion test fail.',format(e))

# 方法二
if u"百度一下,你就知道" == driver.title:
    print('Assertion test pass.')
else:
    print('Assertion test fail.')

print(driver.title)

  

方法一,是利用python中Assert方法,采用包含判断,方法二是通过if方法,采用完全相等方法,建议选择第一种方法。

u"百度一下,你就知道"

  

这u代表unicode的意思,由于这里采用了python2,如果使用python2就不需要,在python3 中,字符串默认采用unicode存储。

二、配置分离版

具体代码;

from selenium import webdriver
import time

# config
url = 'https://baudu.com'
titleCheckString = '百度一下,你就知道'

driver = webdriver.Chrome()
driver.get(url)
print('成功进入网址:',url)
print('当前网址title为:',driver.title)

try:
    assert titleCheckString in driver.title
    print('目标网页标题包含:',titleCheckString)
    print('Assertion test pass.')
except Exception as e:
    print('目标页面标题不包含:',titleCheckString)
    print('Assertion test Fail.',format(e))

  

参考文章:https://blog.csdn.net/u011541946/article/details/69694510

原文地址:https://www.cnblogs.com/zhaocbbb/p/12639775.html