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-8 -*-

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-8 -*-
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-8
#以下代码用来遍历所有复选框
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(2)
'''
checkboxs = driver.find_elements_by_css_selector('input[type=checkbox]')
for checkbox in checkboxs:
    checkbox.click()
    time.sleep(2)
'''
# 把页面上最后1个checkbox 的勾给去掉
#.pop() 方法用于删除并返回数组的最后一个元素,在此处是返回到复选框的“最后一个”按钮
driver.find_elements_by_css_selector('input[type=checkbox]').pop().click()
time.sleep(2)
driver.quit()

 

#coding: utf-8
##以下代码用来遍历所有单选框
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(2)
time.sleep(2)
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-8
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(3)
#将页面滚动条拖到底部
js="var q=document.documentElement.scrollTop=100000"
driver.execute_script(js)
time.sleep(3)
#将滚动条移动到页面的顶部
js="var q=document.documentElement.scrollTop=0"
driver.execute_script(js)
time.sleep(3)
#将页面滚动条移动到页面任意位置,改变等于号后的数值即可
js="var q=document.documentElement.scrollTop=50"
driver.execute_script(js)
time.sleep(999999)
'''
#若要对页面中的内嵌窗口中的滚动条进行操作,要先定位到该内嵌窗口,在进行滚动条操作
js="var q=document.getElementById('id').scrollTop=100000"
driver.execute_script(js)
time.sleep(3)
'''
driver.quit()

 

 方法二:通过键盘 按“DOWN”键,实现页面滚动条滚动到页面任意位置

#coding=utf-8
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(3)
#通过按向下键将页面滚动条拖到底部
driver.find_element_by_xpath("//*[@id='wrapper_wrapper']").send_keys(Keys.DOWN)
time.sleep(1)
driver.find_element_by_xpath("//*[@id='wrapper_wrapper']").send_keys(Keys.DOWN)
time.sleep(1)
driver.find_element_by_xpath("//*[@id='wrapper_wrapper']").send_keys(Keys.DOWN)
time.sleep(1)
driver.find_element_by_xpath("//*[@id='wrapper_wrapper']").send_keys(Keys.DOWN)
time.sleep(1)
driver.find_element_by_xpath("//*[@id='wrapper_wrapper']").send_keys(Keys.DOWN)
time.sleep(1)
driver.find_element_by_xpath("//*[@id='wrapper_wrapper']").send_keys(Keys.DOWN)
time.sleep(1)
driver.find_element_by_xpath("//*[@id='wrapper_wrapper']").send_keys(Keys.DOWN)
time.sleep(3)
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-8 -*-

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)      

        # 把页面上最后1个checkbox 的勾给去掉  
        #.pop() 方法用于删除并返回数组的最后一个元素,在此处是返回到复选框的“最后一个”按钮  
        self._browser.find_elements_by_css_selector('input[type=checkbox]').pop().click()  
        time.sleep(1)  

        # 选择所有的radio并全部勾上  
        radios = self._browser.find_elements_by_css_selector('input[type=radio]')  
        for radio in radios:  
            radio.click()  
            time.sleep(1)  
    
def runMain() :
    client = Client()
    client.test()
        
if __name__ == "__main__":  
    runMain()

 

 

参考资料:

XPATH

http://blog.csdn.net/skylovedaim/article/details/22399749

 

posted @ 2017-06-01 14:02  王信平  阅读(484)  评论(0编辑  收藏  举报