selenium常用的API(三)获取网页title、html源码

获取网页title

获取页面title的方法可以直接用driver.title获取到,然后可以把获取到的结果用做断言。

#encoding=utf-8
from selenium import webdriver
import unittest
import time

class VisitUrl(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Ie(executable_path = "e:\IEDriverServer")

    def test_getTitle(self):
        self.driver.get("http://www.baidu.com")
        # 调用driver的title属性获取页面的title属性值
        title = self.driver.title
        print u"当前网页的title属性值为:", title
        # 断言页面的title属性值是否是“百度一下,你就知道”,如果断言失败则打印"页面title属性值错误!"
        self.assertEqual(title, u"百度一下,你就知道", "页面title属性值错误!")

    def tearDown(self):
        self.driver.quit()

if __name__ == '__main__':
    unittest.main()

获取HTML源码

driver.get("https://www.taobao.com")
# 调用driver的page_source属性获取页面源码
pageSource = driver.page_source
# 打印页面源码
print pageSource.encode("gbk", "ignore")
# 断言页面源码中是否包含“购物”两个关键字,以此判断页面内容是否正确
self.assertTrue(u"购物" in pageSource)
原文地址:https://www.cnblogs.com/zeke-python-road/p/9326590.html