51Testing软件测试论坛

 找回密码
 (注-册)加入51Testing

QQ登录

只需一步,快速开始

微信登录,快人一步

手机号码,快捷登录

查看: 3647|回复: 5
打印 上一主题 下一主题

[讨论] python 用爬虫写网页测试

[复制链接]
  • TA的每日心情
    擦汗
    2022-8-30 09:02
  • 签到天数: 2 天

    连续签到: 2 天

    [LV.1]测试小兵

    跳转到指定楼层
    1#
    发表于 2018-3-15 16:48:47 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
    以测试维基百科为例:
    1. from urllib.request import urlopen
    2. from bs4 import BeautifulSoup
    3. import unittest

    4. class TestWikipedia(unittest.TestCase):
    5.     bsObj = None
    6.     def setUpClass():
    7.         global bsObj
    8.         url = 'http://en.wikipedia.org/wiki/Monty_Python'
    9.         bsObj = BeautifulSoup(urlopen(url))
    10.         print('setting up the test')
    11.     def test_titleTest(self):
    12.         global bsObj
    13.         pageTitle = bsObj.find("h1").get_text()
    14.         self.assertEqual("Monty Python",pageTitle)
    15.         print("tearing down the test")
    16.     def test_contentExists(self):
    17.         global bsObj
    18.         content = bsObj.find("div",{"id":"mw-content-text"})
    19.         self.assertIsNotNone(content)


    20. if __name__=='__main__':
    21.     unittest.main()
    复制代码
    写了两个测试,第一个测试页面标题是否为”Monty Python”,第二个测试页面是否有一个div节
    点id属性是”mw-content-text”
    注意这个页面的内容值加载一次由全局对象bsObj共享给其他测试,这是通过unittest类的函
    数setUpClass来实现的,这个函数只在类的初始化阶段运行一次(与每个测试启动时都运行
    的setUp函数不同),更方便。
    结果:

    1. .setting up the test
    2. tearing down the test
    3. setting up the test..
    4. tearing down the test

    5. ----------------------------------------------------------------------
    6. Ran 3 tests in 2.568s

    7. OK
    复制代码
    注意:单双引号无所谓,用作字符,字符串,注意有转义的时候尽量避免混淆,转单引号则外面用双引
    号,反之亦然,三引号也可以用只是麻烦,另三引号可用作注释
    分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
    收藏收藏
    回复

    使用道具 举报

    本版积分规则

    关闭

    站长推荐上一条 /1 下一条

    小黑屋|手机版|Archiver|51Testing软件测试网 ( 沪ICP备05003035号 关于我们

    GMT+8, 2024-9-20 15:31 , Processed in 0.067337 second(s), 23 queries .

    Powered by Discuz! X3.2

    © 2001-2024 Comsenz Inc.

    快速回复 返回顶部 返回列表