Python学习总结 10 自动化测试Selenium2
一, 配置 Selenium2
1 Selenium是什么?
Selenium是一个用于Web应用程序测试的工具.Selenium 测试直接运行在浏览器中,就像真正的用户在操作一样.支持的浏览器包括IE,Mozilla和Firefox等.这个工具的主要功能包括:测试与浏览器的兼容性--测试你的应用程序看是否能够很好得工作在不同浏览器和操作系统之上.测试系统功能--创建衰退测试检验软件功能和用户需求.
2 安装Selenium
使用pip 命令安装Selenium。
pip install -U selenium
成功安装Selenium后,如下图所示:

3 安装FireFox浏览器驱动
WebDriver支持FireFox,IE,Chrome和Opera等浏览器。还支持Android和IPhone的移动应用测试。
各个浏览器驱动下载地址:
http://www.seleniumhq.org/download/
https://pypi.python.org/pypi/selenium
https://github.com/mozilla/geckodriver/releases
安装FireFox驱动,下载 geckodriver-v0.16.0-win64.zip(根据自己机器操作系统的不同下载不同的驱动),解压得到 geckodriver.exe文件,放到系统环境变量Path下面,前面已经装(C:\Python35)添加到了系统环境变量Path下面,所以可以将geckodriver.exe文件放到 C:\Python35\目录下。
4 安装Chrome浏览器驱动
从http://chromedriver.storage.googleapis.com/index.html?path=2.24/下载Chrome的浏览器驱动。
经过测试发现, ChromeDriver.exe在2.24版本最稳定。
from selenium import webdriver
import os chromedriver = "d:\chromedriver.exe"
os.environ["webdriver.chrome.driver"] = chromedriver options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) driver= webdriver.Chrome( chromedriver,chrome_options=options)
driver.get("http://163.com")
折腾了2天终于正常使用ChromeDriver。
二 案例
1, 例子1, 打开火狐浏览器浏览指定网页
# -*- coding: utf- -*- from selenium import webdriver
from selenium.webdriver.common.keys import Keys browser = webdriver.Firefox()
browser.get('http://www.baidu.com') elem = browser.find_element_by_name('wd') # Find the search box
elem.send_keys('seleniumhq' + Keys.RETURN) browser.quit()
上述代码执行以下操作:
1)打开新的FireFox浏览器
2)找到百度的名字为wd的输入框
3)输入 “seleniumhq”并搜索
4)关闭FireFox浏览器
输如中文关键字,中文需要utf-8格式编码,否则会出错。
# -*- coding: utf- -*-
from selenium import webdriver
from selenium.webdriver.common.keys import Keys browser = webdriver.Firefox()
browser.get('http://www.baidu.com') elem = browser.find_element_by_name('wd') # Find the search box
elem.send_keys(u'老铁 没毛病 双击666' + Keys.RETURN) #browser.quit()
2, selenium_webdriver(python)单/复选框的遍历选择
wml.html
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>Checkbox</title>
</head>
<body>
<h3>checkbox</h3>
<form>
<!-- <label for="c1">checkbox1</label> -->
<input type="checkbox" id="c1" />checkbox1<br>
<!-- <label for="c2">checkbox2</label> -->
<input type="checkbox" id="c2" />checkbox2<br>
<!-- <label for="c3">checkbox3</label> -->
<input type="checkbox" id="c3" />checkbox3<br>
</form> <form>
<label value="radio">radio</label>
<input type="radio" name="sex" value="male" id="as"/><br>
<label value="radio1">radio</label>
<input type="radio" name="sex" value="female" id="sd"/>
</form> <!-- <form>
<input type="radio" name="sex" value="male" /> Male
<br />
<input type="radio" name="sex" value="female" /> Female
</form> --> </body>
</html>
python代码
#coding: utf-
#以下代码用来遍历所有复选框
from selenium import webdriver
import time
import os
driver = webdriver.Chrome()
#获取要测试文件绝对路径
file_path = os.path.abspath('wml.html')
print file_path
#用浏览器打开文件
driver.get(file_path)
# 选择页面上所有的input,然后从中过滤出所有的checkbox 并勾选之
inputs = driver.find_elements_by_tag_name('input')
for input in inputs:
if input.get_attribute('type') == 'checkbox':
input.click()
time.sleep()
'''
checkboxs = driver.find_elements_by_css_selector('input[type=checkbox]')
for checkbox in checkboxs:
checkbox.click()
time.sleep()
'''
# 把页面上最后1个checkbox 的勾给去掉
#.pop() 方法用于删除并返回数组的最后一个元素,在此处是返回到复选框的“最后一个”按钮
driver.find_elements_by_css_selector('input[type=checkbox]').pop().click()
time.sleep()
driver.quit()
#coding: utf-
##以下代码用来遍历所有单选框
from selenium import webdriver
import time
import os
dr = webdriver.Chrome()
file_path = os.path.abspath('wml.html')
dr.get(file_path)
# 选择所有的radio并全部勾上
radios = dr.find_elements_by_css_selector('input[type=radio]')
for radio in radios:
radio.click()
time.sleep()
time.sleep()
dr.quit()
3, 加载本地资源
loginURL = 'http://www.zhihu.com'
self._browser = webdriver.Firefox()
self._browser.get( self.loginURL )
4, 调用JavaScript
def execute_script(self, script, *args):
"""
Synchronously Executes JavaScript in the current window/frame. :Args:
- script: The JavaScript to execute.
- \*args: Any applicable arguments for your JavaScript. :Usage:
driver.execute_script('document.title')
"""
converted_args = list(args)
return self.execute(Command.EXECUTE_SCRIPT,
{'script': script, 'args':converted_args})['value']
例子1,
首先,直接传入Javascript代码
jse.executeScript("window.document.getElementById('jingshou').click()"
然后,传入WebElement执行JS
WebElement element = driver.findElement(By.id("jingshou"));
jse.executeScript("arguments[0].click();", element);
例子2,
首先,新建一个Python类来读取js文件。CommonHelper.py
class CommonHelper :
def __init__(self ) :
pass @staticmethod
def readJs( style):
with open( style , 'r') as f:
return f.read()
然后使用selenium2
f = webdriver.Firefox()
f.get("file://path/to/empty.html") from selenium import webdriver f = webdriver.Firefox()
f.execute_script("window.blah = function () {document.body.innerHTML='testing';}")
f.execute_script("blah()")
也可以执行简单js代码,如下所示:
driver.execute_script("window.a = function(a,b) {return a + b;}")
print driver.execute_script("return a(1,2)")
例子3, 控制浏览器滚动条
方法一:调过JS脚本控制
#coding=utf-
from selenium import webdriver
import time
#访问百度
driver=webdriver.Firefox()
driver.get("http://www.baidu.com")
#搜索
driver.find_element_by_id("kw").send_keys("selenium")
driver.find_element_by_id("su").click()
time.sleep()
#将页面滚动条拖到底部
js="var q=document.documentElement.scrollTop=100000"
driver.execute_script(js)
time.sleep()
#将滚动条移动到页面的顶部
js="var q=document.documentElement.scrollTop=0"
driver.execute_script(js)
time.sleep()
#将页面滚动条移动到页面任意位置,改变等于号后的数值即可
js="var q=document.documentElement.scrollTop=50"
driver.execute_script(js)
time.sleep()
'''
#若要对页面中的内嵌窗口中的滚动条进行操作,要先定位到该内嵌窗口,在进行滚动条操作
js="var q=document.getElementById('id').scrollTop=100000"
driver.execute_script(js)
time.sleep()
'''
driver.quit()
方法二:通过键盘 按“DOWN”键,实现页面滚动条滚动到页面任意位置
#coding=utf-
from selenium import webdriver
import time
from selenium.webdriver.common.keys import Keys
#访问百度
driver=webdriver.Firefox()
driver.get("http://www.baidu.com")
#搜索
driver.find_element_by_id("kw").send_keys("selenium")
driver.find_element_by_id("su").click()
time.sleep()
#通过按向下键将页面滚动条拖到底部
driver.find_element_by_xpath("//*[@id='wrapper_wrapper']").send_keys(Keys.DOWN)
time.sleep()
driver.find_element_by_xpath("//*[@id='wrapper_wrapper']").send_keys(Keys.DOWN)
time.sleep()
driver.find_element_by_xpath("//*[@id='wrapper_wrapper']").send_keys(Keys.DOWN)
time.sleep()
driver.find_element_by_xpath("//*[@id='wrapper_wrapper']").send_keys(Keys.DOWN)
time.sleep()
driver.find_element_by_xpath("//*[@id='wrapper_wrapper']").send_keys(Keys.DOWN)
time.sleep()
driver.find_element_by_xpath("//*[@id='wrapper_wrapper']").send_keys(Keys.DOWN)
time.sleep()
driver.find_element_by_xpath("//*[@id='wrapper_wrapper']").send_keys(Keys.DOWN)
time.sleep()
driver.quit()
例子4 单/复选框的遍历选择
wml.html:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>Checkbox</title> </head>
<body> <h3>checkbox</h3>
<form>
<input type="checkbox" id="c1" />checkbox1<br>
<input type="checkbox" id="c2" />checkbox2<br>
<input type="checkbox" id="c3" />checkbox3<br>
</form> <h3>Radio</h3>
<form>
<label value="radio">radio</label>
<input type="radio" name="sex" value="male" id="as"/><br>
<label value="radio1">radio</label>
<input type="radio" name="sex" value="female" id="sd"/>
</form> </body>
</html>
测试脚本
# -*- coding: utf- -*- from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import time
from db import HandleDatabase
from CommonHelper import CommonHelper
import os class Client(object):
testUrl = 'http://127.0.0.1:8020/TestWeb/xpath.html' def __init__(self):
self.initChrome() def initChrome( self ):
chromedriver = "d:\chromedriver.exe"
os.environ["webdriver.chrome.driver"] = chromedriver
options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"])
self._browser= webdriver.Chrome( chromedriver,chrome_options=options) def test( self):
self._browser.get( self.testUrl )
# 选择页面上所有的input,然后从中过滤出所有的checkbox 并勾选之
inputs = self._browser.find_elements_by_tag_name('input')
for input in inputs:
if input.get_attribute('type') == 'checkbox':
input.click()
time.sleep() # 把页面上最后1个checkbox 的勾给去掉
#.pop() 方法用于删除并返回数组的最后一个元素,在此处是返回到复选框的“最后一个”按钮
self._browser.find_elements_by_css_selector('input[type=checkbox]').pop().click()
time.sleep() # 选择所有的radio并全部勾上
radios = self._browser.find_elements_by_css_selector('input[type=radio]')
for radio in radios:
radio.click()
time.sleep() def runMain() :
client = Client()
client.test() if __name__ == "__main__":
runMain()
参考资料:
XPATH
http://blog.csdn.net/skylovedaim/article/details/22399749
Python学习总结 10 自动化测试Selenium2的更多相关文章
- python 学习笔记 10 -- 正則表達式
零.引言 在<Dive into Python>(深入python)中,第七章介绍正則表達式,开篇非常好的引出了正則表達式,以下借用一下:我们都知道python中字符串也有比較简单的方法, ...
- python学习笔记10(Python的内存管理)
用这张图激励一下自己,身边也就只有一位全栈数据工程师!!! 32. Python的内存管理 1. 对象的内存使用 对于整型和短字符串对象,一般内存中只有一个存储,多次引用.其他的长字符串和其他对象 ...
- Python 学习笔记10
念念不忘,必有回响. 今天继续学习Python 类.
- 从零开始的Python学习Episode 10——函数
函数 一.函数的创建 简单格式 def function_name(参数表): 函数体 return 如果没有写return,函数会默认返回一个none 二.函数的参数 必需参数: 调用函数时必需参数 ...
- Python学习:10.Python装饰器讲解(一)
情景介绍 一天,在你正在努力加班的时候,老板给交给你了一个任务,就是在这段代码里将所有函数开始输出一个‘hello’最后输出当前时间,再输出一个“end”,这段代码里包含了大量的函数,你会怎么做? d ...
- python学习笔记10 ----网络编程
网络编程 网络编程需要知道的概念 网络体系结构就是使用这些用不同媒介连接起来的不同设备和网络系统在不同的应用环境下实现互操作性,并满足各种业务需求的一种粘合剂.网络体系结构解决互质性问题彩是分层方法. ...
- python学习笔记(10):面向对象
一.类和实例 1.类(Class): 用来描述具有相同的属性和方法的对象的集合.它定义了该集合中每个对象所共有的属性和方法.对象是类的实例. 2.对象:通过类定义的数据结构实例.对象包括两个数据成员( ...
- python学习(10)字典学习,写一个三级菜单程序
学习了字典的应用.按老师的要求写一个三级菜单程序. 三级菜单程序需求如下: 1.深圳市的区--街道--社区---小区4级 2.建立一个字典,把各级区域都装进字典里 3.用户可以从1级进入2级再进入3级 ...
- Python学习笔记10
1.函数式编程 理论就来自lambda演算,虽然没有学过lisp,一直被其大名震撼. 特性: 函数是以一等公民 可以作为参数 可以作为返回值 具有闭包特性 1.1参数传递方式 一般参数传递 ...
随机推荐
- iOS------自动查找项目中不用的图片资源
注意:删除的时候要谨慎!别什么图都删了,看看对项目有没有作用.这个插件有时也会有一定的误差. 具体操作步骤: 1.去github上下载LSUnusedResources(下载地址:https://gi ...
- jsfiddle 使用教程
最近有许多的Css 3 demo,因此为了方便查阅,就将demo部分放在jsfiddle ,方便日后翻阅. 这是 JSFIDDLE 的官网文档,都是英文,不过对照看还是可以的:官方文档 HTML区域: ...
- [20181031]12c 在线移动数据文件.txt
[20181031]12c 在线移动数据文件.txt --//12c以前,移动或者改名数据文件是一项比较麻烦的事情,至少要停一下业务.而12c支持在线移动或者改名数据文件,并且有点不可思议--//的是 ...
- mssql sqlserver 下文分享一种新颖的字符串截取方法
原文地址:http://www.maomao365.com/?p=7307 摘要: 以前分割字符串时,都使用类似split函数的方式处理,下文分享一种对有规律的字符串的分隔方式, 即:1. ...
- SQL Server将一列的多行内容拼接成一行
昨天遇到一个SQL Server的问题:需要写一个储存过程来处理几个表中的数据,最后问题出在我想将一个表的一个列的多行内容拼接成一行 比如表中有两列数据 : ep_classes ep_name A ...
- c/c++ 数组的智能指针 使用
数组的智能指针 使用 数组的智能指针的限制: 1,unique_ptr的数组智能指针,没有*和->操作,但支持下标操作[] 2,shared_ptr的数组智能指针,有*和->操作,但不支持 ...
- 平衡二叉树(Balanced Binary Tree 或 Height-Balanced Tree)又称AVL树
平衡二叉树(Balanced Binary Tree 或 Height-Balanced Tree)又称AVL树 (a)和(b)都是排序二叉树,但是查找(b)的93节点就需要查找6次,查找(a)的93 ...
- java 一个实例
this 代替
- 通用Logging框架设计
项目开发中,大家都会使用日志框架(LogBack, log4j , java.util.logging 等).下面来简单的了解一下日志框架的大体设计思路. 类图:
- vuejs2+webpack2+vuxui2多页面架手脚,支持二级目录
const UglifyJsPlugin = require('uglifyjs-webpack-plugin') // 去console插件 const CompressionWebpackPlug ...