Python网络数据采集7-单元测试与Selenium自动化测试
Python网络数据采集7-单元测试与Selenium自动化测试
单元测试
Python中使用内置库unittest可完成单元测试。只要继承unittest.TestCase类,就可以实现下面的功能。
- 为每个单元测试的开始和结束提供
setUp和tearDown函数。 - 提供不同类型的断言让测试成功或者失败
- 所有以
test_打头的函数,都会当成单元测试来运行,他们彼此独立,互不影响。
下面来看一个简单的例子
import unittest
class TestSimple(unittest.TestCase):
def setUp(self):
print('set up')
def test_simple(self):
a = 2
l = [2, 3, 43]
self.assertIn(a, l)
def tearDown(self):
print('teardown')
if __name__ == '__main__':
unittest.main(argv=['ignored', '-v'], exit=False)
test_simple (__main__.TestSimple) ...
set up
teardown
ok
----------------------------------------------------------------------
Ran 1 test in 0.006s
OK
在Jupyter中,main()需要填入以上参数才能运行,参数列表中第一个参数会被忽略,而exit=False则不会kill掉kernel。详见stackoverflow
但是在Pycharm中运行则不会任何参数。
测试维基百科
将Python的单元测试和网络爬虫结合起来,就可以实现简单的网站前端功能测试。
import requests
from bs4 import BeautifulSoup
import unittest
class TestWiki(unittest.TestCase):
soup = None
def setUp(self):
global soup
r = requests.get('https://en.wikipedia.org/wiki/Monty_Python')
soup = BeautifulSoup(r.text, 'lxml')
def test_title(self):
global soup
title = soup.h1.string
self.assertEqual(title, 'Monty Python')
def test_content_exists(self):
global soup
content = soup.find('div', id='mw-content-text')
self.assertIsNotNone(content)
if __name__ == '__main__':
unittest.main(argv=['ignored', '-v'], exit=False)
test_simple (__main__.TestSimple) ... ok
test_content_exists (__main__.TestWiki) ...
set up
teardown
D:\Anaconda3\lib\site-packages\bs4\builder\_lxml.py:250: DeprecationWarning: inspect.getargspec() is deprecated, use inspect.signature() or inspect.getfullargspec()
self.parser.feed(markup)
ok
test_title (__main__.TestWiki) ... ok
----------------------------------------------------------------------
Ran 3 tests in 3.651s
OK
Selenium单元测试
如果使用selenium进行网站测试呢?(它的初衷就是用来干这个的)
from selenium import webdriver
driver = webdriver.PhantomJS(executable_path=r'C:\Program Files (x86)\phantomjs\bin\phantomjs.exe')
driver.get('https://en.wikipedia.org/wiki/Monty_Python')
print(driver.title)
assert 'Monty Python' in driver.title
Monty Python - Wikipedia
from selenium import webdriver
driver = webdriver.PhantomJS(executable_path=r'C:\Program Files (x86)\phantomjs\bin\phantomjs.exe')
driver.get('http://pythonscraping.com/pages/files/form.html')
# 找到输入框和提交按钮
first_name = driver.find_element_by_name('firstname')
last_name = driver.find_element_by_name('lastname')
submit = driver.find_element_by_id('submit')
# 输入
first_name.send_keys('admin')
last_name.send_keys('Sun')
# 提交
submit.click()
print(driver.find_element_by_tag_name('body').text)
driver.close()
Hello there, admin Sun!
或者使用动作链。
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver import ActionChains
driver = webdriver.PhantomJS(executable_path=r'C:\Program Files (x86)\phantomjs\bin\phantomjs.exe')
driver.get('http://pythonscraping.com/pages/files/form.html')
# 找到输入框和提交按钮
first_name = driver.find_element_by_name('firstname')
last_name = driver.find_element_by_name('lastname')
submit = driver.find_element_by_id('submit')
actions = ActionChains(driver).send_keys_to_element(first_name, 'admin') \
.send_keys_to_element(last_name, 'Sun') \
.send_keys(Keys.ENTER)
# 执行动作链
actions.perform()
print(driver.find_element_by_tag_name('body').text)
driver.close()
Hello there, admin Sun!
除了简单的单击双击,发送文本到输入框,还能实现复杂的动作。比如拖放。
from selenium import webdriver
from selenium.webdriver import ActionChains
driver = webdriver.Firefox()
driver.get('http://pythonscraping.com/pages/javascript/draggableDemo.html')
print(driver.find_element_by_id('message').text)
element = driver.find_element_by_id('draggable')
target = driver.find_element_by_id('div2')
actions = ActionChains(driver).drag_and_drop(element, target)
actions.perform()
print(driver.find_element_by_id('message').text)
driver.close()
Prove you are not a bot, by dragging the square from the blue area to the red area!
You are definitely not a bot!
上面的代码用FireFox可以成功,Chrome和PhantomJs不成功,不知道为什么。先是打印了未拖拽方块时候显示的文字,当将方块拖到下面的div区域之后,页面上的文字变化了。
Selenium还有个有意思的功能--截屏。
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver import ActionChains
driver = webdriver.PhantomJS(executable_path=r'C:\Program Files (x86)\phantomjs\bin\phantomjs.exe')
driver.get('https://www.pythonscraping.com/')
driver.get_screenshot_as_file('screenshot.png')
True
保存成功就会返回打印True。
Selenium与单元测试结合
还是面拖拽的例子,加入了Python单元测试与Selenium结合使用。
from selenium import webdriver
from selenium.webdriver import ActionChains
import unittest
class TestSelenium(unittest.TestCase):
driver = None
def setUp(self):
global driver
driver = webdriver.Firefox()
driver.get('http://pythonscraping.com/pages/javascript/draggableDemo.html')
def test_drag(self):
global driver
element = driver.find_element_by_id('draggable')
target = driver.find_element_by_id('div2')
actions = ActionChains(driver).drag_and_drop(element, target)
actions.perform()
self.assertEqual('You are definitely not a bot!', driver.find_element_by_id('message').text)
if __name__ == '__main__':
unittest.main(argv=['ignored', '-v'], exit=False)
test_drag (__main__.TestSelenium) ... ok
test_simple (__main__.TestSimple) ... ok
test_content_exists (__main__.TestWiki) ...
set up
teardown
D:\Anaconda3\lib\site-packages\bs4\builder\_lxml.py:250: DeprecationWarning: inspect.getargspec() is deprecated, use inspect.signature() or inspect.getfullargspec()
self.parser.feed(markup)
ok
test_title (__main__.TestWiki) ... ok
----------------------------------------------------------------------
Ran 4 tests in 23.923s
OK
依然得使用FireFox, 以及main中加上参数argv=['ignored', '-v'], exit=False。看打印结果,上面的测试也执行了,好像在Jupyter中,虽然在一个Cell中执行单元测试,所有测试都会得到执行。普通Python代码就不是这样,每个Cell独立运行,还可以使用上面Cell定义过的变量和已经导入的库。
by @sunhaiyu
2017.7.19
Python网络数据采集7-单元测试与Selenium自动化测试的更多相关文章
- [python] 网络数据采集 操作清单 BeautifulSoup、Selenium、Tesseract、CSV等
Python网络数据采集操作清单 BeautifulSoup.Selenium.Tesseract.CSV等 Python网络数据采集操作清单 BeautifulSoup.Selenium.Tesse ...
- 笔记之Python网络数据采集
笔记之Python网络数据采集 非原创即采集 一念清净, 烈焰成池, 一念觉醒, 方登彼岸 网络数据采集, 无非就是写一个自动化程序向网络服务器请求数据, 再对数据进行解析, 提取需要的信息 通常, ...
- Python网络数据采集PDF高清完整版免费下载|百度云盘
百度云盘:Python网络数据采集PDF高清完整版免费下载 提取码:1vc5 内容简介 本书采用简洁强大的Python语言,介绍了网络数据采集,并为采集新式网络中的各种数据类型提供了全面的指导.第 ...
- Python网络数据采集6-隐含输入字段
Python网络数据采集6-隐含输入字段 selenium的get_cookies可以轻松获取所有cookie. from pprint import pprint from selenium imp ...
- Python网络数据采集4-POST提交与Cookie的处理
Python网络数据采集4-POST提交与Cookie的处理 POST提交 之前访问页面都是用的get提交方式,有些网页需要登录才能访问,此时需要提交参数.虽然在一些网页,get方式也能提交参.比如h ...
- Python网络数据采集3-数据存到CSV以及MySql
Python网络数据采集3-数据存到CSV以及MySql 先热热身,下载某个页面的所有图片. import requests from bs4 import BeautifulSoup headers ...
- Python网络数据采集2-wikipedia
Python网络数据采集2-wikipedia 随机链接跳转 获取维基百科的词条超链接,并随机跳转.可能侧边栏和低栏会有其他链接.这不是我们想要的,所以定位到正文.正文在id为bodyContent的 ...
- Python网络数据采集1-Beautifulsoup的使用
Python网络数据采集1-Beautifulsoup的使用 来自此书: [美]Ryan Mitchell <Python网络数据采集>,例子是照搬的,觉得跟着敲一遍还是有作用的,所以记录 ...
- Python网络数据采集PDF
Python网络数据采集(高清版)PDF 百度网盘 链接:https://pan.baidu.com/s/16c4GjoAL_uKzdGPjG47S4Q 提取码:febb 复制这段内容后打开百度网盘手 ...
随机推荐
- curl的使用
curl -v -0 -T 123.wav "127.0.0.1:80/saveSound?filename=18696770041_1379903830_xxx.wav&du ...
- TCP连接中time_wait在开发中的影响-搜人以鱼不如授之以渔
根据TCP协议定义的3次握手断开连接规定,发起socket主动关闭的一方socket将进入TIME_WAIT状态,TIME_WAIT状态将持续2个MSL(Max Segment Lifetime),T ...
- VMWare、KVM、Virtualbox克隆或复制Linux虚拟机后eth0找不到的解决方案
快速处理办法: cat /etc/sysconfig/network-scripts/ifcfg-eth0 sed -i '/UUID/d' /etc/sysconfig/network-script ...
- MVC过滤器之添加LoginAttribute,浏览器bug:重定向次数太多
以前在写登录Action过滤时,都在每个Controller前写上CheckLoginAttribute:这次决定偷懒试一下能否将所有Action和Controller统一过滤: 出bug的代码是这样 ...
- [leetcode-504-Base 7]
Given an integer, return its base 7 string representation. Example 1: Input: 100 Output: "202&q ...
- Chapter 5. MPEG-4 Visual
本章着重介绍有关MPEG-4 Visual标准的细节. Tool 编码工具集合的子集(比如支持交织等). Object 视频元素(比如一个矩形视频帧,或者一个任意形状的区域,静止的图像). Profi ...
- 自动化测试—monkeyrunner
步骤: 1. 在 pycharm 中编写一个 python的脚本,注意:在运行脚本时不要有注释,不然会报错 2. 在 dos 窗口中运行脚本. ...
- HTML Element 与 Node 的区别
Element 与 Node 的区别 <html> <head><title>Element & Node</title></head&g ...
- 在SOUI中使用网格布局
在实现网格布局前,SOUI支持两种布局形式:相对布局,和线性布局,其中线性布局是2017年2月份才支持的布局. 这两年工作都在Android这里,Android里有号称5大布局(RelativeLay ...
- kbengine_js_plugins 在Cocos Creator中适配
kbengine_js_plugins 改动(2017/7/6) 由于Cocos Creator使用严格模式的js,而原本的kbengine_js_plugins是非严格模式的,因此为了兼容和方 便C ...