python webdriver api-读取、设置配置文件
文件结构:
db.ini放置db信息的配置文件
文件中[gloryroad]是section信息
下边的dbname等是option信息
UiObjectMap.ini放置访问web的配置信息
配置用到的xpath元素信息-做到数据和程序的分离
第一步读取配置文件
把配置文件放到当前脚本所在目录下
#encoding=utf-8
import ConfigParser
import os
import platform
if platform.system() == "Windows":
configFilePath = os.path.dirname(os.path.abspath(__file__)) + "\db.ini"
else:
configFilePath = os.path.dirname(os.path.abspath(__file__)) + "/db.ini"
print "path:",configFilePath
cf = ConfigParser.ConfigParser()#专门解析ini文件的,python的类
cf.read(configFilePath)#实例化后,进行读取,拼成完全路径
print cf.sections()#section就是方括号的内容
print cf.options("gloryroad")#获取gloryroad的section下边的所有的配置选项
dbname = cf.get("gloryroad","dbname")#获取gloryroad下边dbname的值
username = cf.get("gloryroad","username")
password = cf.get("gloryroad","password")
webserver= cf.get("web","webserver")
print dbname
print username
print password
print webserver
D:\test>python test.py
path: D:\test\db.ini
['gloryroad', 'web', 'linux']
['dbname', 'username', 'password']
gloryroad
root
gloryroadwulaoshi
127.0.0.1
加了打印__file__,os.path.abspath(__file__)
#encoding=utf-8
import ConfigParser
import os
import platform
print __file__
print os.path.abspath(__file__)
if platform.system()=='Windows':
configFilePath=os.path.dirname(os.path.abspath(__file__))+'\db.ini'
else:
configFilePath=os.path.dirname(os.path.abspath(__file__))+'/db.ini'
print "path:",configFilePath
cf=ConfigParser.ConfigParser()
cf.read(configFilePath)
print cf.sections()
print cf.options("gloryroad")
dbname=cf.get("gloryroad","dbname")
username=cf.get("gloryroad",'username')
password=cf.get("gloryroad","password")
webserver=cf.get("web","webserver")
print dbname
print username
print password
print webserver
D:\test>python test.py
test.py
D:\test\test.py
path: D:\test\db.ini
['gloryroad', 'web', 'linux']
['dbname', 'username', 'password']
gloryroad
root
gloryroadwulaoshi
127.0.0.1
自己调试:
#encoding=utf-8
import ConfigParser
import os
import platform
if platform.system() == "Windows":
configFilePath = os.path.dirname(os.path.abspath(__file__)) + "\gloryxia.ini"
else:
configFilePath = os.path.dirname(os.path.abspath(__file__)) + "/gloryxia.ini"
print "path:",configFilePath
cf = ConfigParser.ConfigParser()#专门解析ini文件的,python的类
cf.read(configFilePath)#实例化后,进行读取,拼成完全路径
print cf.sections()#section就是方括号的内容
print cf.options("xiaxiaoxu")#获取gloryroad的section下边的所有的配置选项
gender = cf.get("xiaxiaoxu","gender")#获取gloryroad下边dbname的值
age = cf.get("xiaxiaoxu","age")
carrer = cf.get("xiaxiaoxu","carrer")
print gender
print age
print carrer
D:\test>python test.py
path: D:\test\gloryxia.ini
['xiaxiaoxu']
['gender', 'age', 'carrer']
male
32
tester
封装成函数
#encoding=utf-8
import ConfigParser
import os
import platform
def read_ini_file(ini_file_path,section_name,option_name):
cf = ConfigParser.ConfigParser()
cf.read(ini_file_path)
try:
value = cf.get(section_name,option_name)
except:
print "the specific seciton or the specific option doesn't exit!"
return None
else:
return value
print read_ini_file(os.path.dirname(os.path.abspath(__file__)) + "\gloryxia.ini","xiaxiaoxu","carrer")
D:\test>python test.py
tester
修改:
#encoding=utf-8
import ConfigParser
import os
import platform
def read_ini_file(ini_path,section_name,option):
cf=ConfigParser.ConfigParser()
cf.read(ini_path)
try:
value=cf.get(section_name,option)
except:
print "option of '%s' is not existed!"%section_name
return None
else:
return "option '%s' of section '%s' is '%s'"%(option,section_name,value)
print read_ini_file('d:\\test\\db.ini','gloryroad','dbname')
print read_ini_file('d:\\test\\db.ini','gloryroad','username')
print read_ini_file('d:\\test\\db.ini','gloryroad','password')
print read_ini_file('d:\\test\\db.ini','web','webserver')
D:\test>python test.py
option 'dbname' of section 'gloryroad' is 'gloryroad'
option 'username' of section 'gloryroad' is 'root'
option 'password' of section 'gloryroad' is 'gloryroadwulaoshi'
option 'webserver' of section 'web' is '127.0.0.1'
第二步怎么分割配置文件
指定浏览器,section(网站名),和元素名(element_name)
UiObjectMap.ini:
[sogou]
searchBox=id>query
searchButton=id>stb
脚本:
#encoding=utf-8
from selenium.webdriver.support.ui import WebDriverWait
import ConfigParser
import os
from selenium import webdriver
class ObjectMap(object):
def __init__(self):#这里把文件路径写死了,可以在封装时把路径作为参数传进去
# 获取存放页面元素定位表达方式及定位表达式的配置文件所在绝对路径
# os.path.abspath(__file__)表示获取当前文件所在路径目录
self.uiObjMapPath = os.path.dirname(os.path.abspath(__file__))\
+ "\\UiObjectMap.ini"
print self.uiObjMapPath
def getElementObject(self, driver, webSiteName, elementName):
try:
# 创建一个读取配置文件的实例
cf = ConfigParser.ConfigParser()
# 将配置文件内容加载到内存
cf.read(self.uiObjMapPath)
# 根据section和option获取配置文件中页面元素的定位方式及
# 定位表达式组成的字符串,并使用“>”分割
locators = cf.get(webSiteName, elementName).split(">")
# 得到定位方式
locatorMethod = locators[0]
# 得到定位表达式
locatorExpression = locators[1]
print locatorMethod, locatorExpression
# 通过显示等待方式获取页面元素
element = WebDriverWait(driver, 10).until(lambda x: \
x.find_element(locatorMethod, locatorExpression))
except Exception, e:
raise e
else:
# 当页面元素被找到后,将该页面元素对象返回给调用者
return element
if __name__ == '__main__':
driver = webdriver.Firefox(executable_path = "d:\\geckodriver")
url = "http://www.sogou.com"
driver.get(url)
print driver.find_element("id","stb")
objmap =ObjectMap()
print objmap.getElementObject(driver,"sogou","searchBox")
print objmap.getElementObject(driver,"sogou","searchButton")
D:\test>python test.py
<selenium.webdriver.firefox.webelement.FirefoxWebElement (session="34bb42dc-7a7c-4bfe-9e6c-dcafdcdc99f1", element="a238abd6-a1dc-48eb-ab7a-e18dbdc1e4ca")>
D:\test\UiObjectMap.ini
id query
<selenium.webdriver.firefox.webelement.FirefoxWebElement (session="34bb42dc-7a7c-4bfe-9e6c-dcafdcdc99f1", element="060bb8c0-c4b4-49d1-845b-0c57e921d216")>
id stb
<selenium.webdriver.firefox.webelement.FirefoxWebElement (session="34bb42dc-7a7c-4bfe-9e6c-dcafdcdc99f1", element="a238abd6-a1dc-48eb-ab7a-e18dbdc1e4ca")>
第三步结合搜狗的使用进行点击
ObjectMap.py:
#encoding=utf-8
from selenium.webdriver.support.ui import WebDriverWait
import ConfigParser
import os
from selenium import webdriver
class ObjectMap(object):
def __init__(self):
# 获取存放页面元素定位表达方式及定位表达式的配置文件所在绝对路径
# os.path.abspath(__file__)表示获取当前文件所在路径目录
self.uiObjMapPath = os.path.dirname(os.path.abspath(__file__))\
+ "\\UiObjectMap.ini"
print self.uiObjMapPath
def getElementObject(self, driver, webSiteName, elementName):
try:
# 创建一个读取配置文件的实例
cf = ConfigParser.ConfigParser()
# 将配置文件内容加载到内存
cf.read(self.uiObjMapPath)
# 根据section和option获取配置文件中页面元素的定位方式及
# 定位表达式组成的字符串,并使用“>”分割
locators = cf.get(webSiteName, elementName).split(">")
# 得到定位方式
locatorMethod = locators[0]
# 得到定位表达式
locatorExpression = locators[1]
print locatorMethod, locatorExpression
# 通过显示等待方式获取页面元素
element = WebDriverWait(driver, 10).until(lambda x: \
x.find_element(locatorMethod, locatorExpression))
except Exception, e:
raise e
else:
# 当页面元素被找到后,将该页面元素对象返回给调用者
return element
if __name__ == '__main__':
driver = webdriver.Ie(executable_path = "e:\\IEDriverServer")
url = "http://www.sogou.com"
driver.get(url)
print driver.find_element("id","stb")
objmap =ObjectMap()
print objmap.getElementObject(driver,"sogou","searchBox")
print objmap.getElementObject(driver,"sogou","searchButton")
UiObjectMap.ini:
[sogou]
searchBox=id>query
searchButton=id>stb
脚本:
#encoding=utf-8
from selenium import webdriver
import unittest
import time, traceback
from ObjectMap import ObjectMap
class TestSoGouByObjectMap(unittest.TestCase):
def setUp(self):
self.obj = ObjectMap()
# 启动Firefox浏览器
self.driver = webdriver.Firefox(executable_path = "c:\\geckodriver")
def testSoGouSearch(self):
url = "http://www.sogou.com"
# 访问搜狗首页
self.driver.get(url)
try:
# 查找页面搜索输入框
searchBox = self.obj.getElementObject\
(self.driver, "sogou", "searchBox")
# 在找到的搜索输入框中输入“WebDriver实战宝典”
searchBox.send_keys(u"WebDriver实战宝典")
# 查找搜索按钮
searchButton = self.obj.getElementObject\
(self.driver, "sogou", "searchButton")
# 点击找到的搜索按钮
searchButton.click()
# 等待2秒,以便页面加载完成
time.sleep(2)
# 断言关键字“吴晓华”是否按预期出现在页面源代码中
self.assertTrue(u"吴晓华" in self.driver.page_source, "assert error!")
except Exception, e:
# 打印异常堆栈信息
print traceback.print_exc()
def tearDown(self):
# 退出IE浏览器
self.driver.quit()
if __name__ == '__main__':
unittest.main()
D:\test>python test.py
D:\test\UiObjectMap.ini
id query
id stb
.
----------------------------------------------------------------------
Ran 1 test in 56.168s
OK
python webdriver api-读取、设置配置文件的更多相关文章
- python的ConfigParser读取设置配置文件
python 读写配置文件在实际应用中具有十分强大的功能,在实际的操作中也有相当简捷的操作方案,以下的文章就是对python 读写配置文件的具体方案的介绍,望你浏览完下面的文章会有所收获. pytho ...
- 转:python webdriver API 之设置等待时间
有时候为了保证脚本运行的稳定性,需要脚本中添加等待时间.sleep(): 设置固定休眠时间. python 的 time 包提供了休眠方法 sleep() , 导入 time 包后就可以使用 slee ...
- 转:python webdriver API 之下载文件
webdriver 允许我们设置默认的文件下载路径.也就是说文件会自动下载并且存在设置的那个目录中.要想下载文件,首选要先确定你所要下载的文件的类型.要识别自动文件的下载类型可以使用 curl ,如图 ...
- 转:python webdriver API 之操作测试对象
一般来说,所有有趣的操作与页面交互都将通过 WebElement 接口,包括上一节中介绍的对象定位,以及本节中需要介绍的常对象操作.webdriver 中比较常用的操作元素的方法有下面几个: cle ...
- 转:python webdriver API 之cookie 处理
有时候我们需要验证浏览器中是否存在某个 cookie,因为基于真实的 cookie 的测试是无法通过白盒和集成测试完成的.webdriver 可以读取.添加和删除 cookie 信息.webdrive ...
- 转:python webdriver API 之简单对象的定位
对象(元素)的定位和操作是自动化测试的核心部分,其中操作又是建立在定位的基础上的,因此元素定位就显得非常重要. (本书中用到的对象与元素同为一个事物)一个对象就像是一个人,他会有各种的特征(属性) , ...
- 转:python webdriver API 之 验证码问题
对于 web 应用来说,大部分的系统在用户登录时都要求用户输入验证码,验证码的类型的很多,有字母数字的,有汉字的,甚至还要用户输入一条算术题的答案的,对于系统来说使用验证码可以有效果的防止采用机器猜测 ...
- 转:python webdriver API 之浏览器的操作
1.1.浏览器最大化在统一的浏览器大小下运行用例,可以比较容易的跟一些基于图像比对的工具进行结合,提升测试的灵活性及普遍适用性.比如可以跟 sikuli 结合,使用 sikuli 操作 flash.# ...
- 转:python webdriver API 之调用 JavaScript
当 webdriver 遇到没法完成的操作时,笔者可以考虑借用 JavaScript 来完成,比下下面的例子,通过 JavaScript 来隐藏页面上的元素.除了完成 webdriver 无法完成的操 ...
- 转:python webdriver API 之alert/confirm/prompt 处理
webdriver 中处理 JavaScript 所生成的 alert.confirm 以及 prompt 是很简单的.具体思路是使用switch_to.alert()方法定位到 alert/conf ...
随机推荐
- logstash实战filter插件之grok(收集apache日志)
有些日志(比如apache)不像nginx那样支持json可以使用grok插件 grok利用正则表达式就行匹配拆分 预定义的位置在 /opt/logstash/vendor/bundle/jruby/ ...
- java中List的toArray方法
把List转换成某种类型的数组,就拿String类型来做例子吧,有以下两种方式: //方法1,使用不带参数的toArray方法 String[] arr1=new String[list.size() ...
- FaceBook开源的词向量计算框架
fasttext是个好东西,是由facebook在2016年推出的一个训练词向量的模型.相比于之前Google的word2vec,fasttext可以解决out of vocabulary的问题.fa ...
- 批量转换gbk编码的java代码为utf8
#!/bin/bash echo $1 echo $# if [ ! $# -eq 1 ]; then echo "usage: ./gbk2utf8.sh src" ...
- mysql ifnull判断为空设置默认值
IFNULL(count,0) as count select IFNULL(count,0) as count from table_name 可以设置当某个字段为空的时候默认值.
- flask中cookie,session的存储,调用,删除 方法(代码demo)
# -*- encoding: utf-8 -*- # cookie,session的存储,调用,删除 from flask import Flask,make_response,request,se ...
- Unity3D中使用Profiler精确定位性能热点的优化技巧
本文由博主(SunboyL)原创,转载请注明出处:http://www.cnblogs.com/xsln/p/BeginProfiler.html 简介 在使用Profiler定位代码的性能热点时,很 ...
- linux桌面与命令模式切换
在图形下面按Ctrl+alt+F1(F2\F3\F4)进入命令模式 在命令模式下,按Ctrl+alt+F7回到图形,或登录用户输入startx进入图形!
- Pycharm自动换行
只对当前文件有效的操作是菜单栏->View -> Active Editor -> Use Soft Wraps. 要是想对所有文件都起到效果,就要在setting里面进行操作.Pe ...
- 【剑指offer】包含min函数的栈
一.题目: 定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数. 二.思路: 无,Z(zhi)Z(zhang)式操作. 三.代码: