文件结构:

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-读取、设置配置文件的更多相关文章

  1. python的ConfigParser读取设置配置文件

    python 读写配置文件在实际应用中具有十分强大的功能,在实际的操作中也有相当简捷的操作方案,以下的文章就是对python 读写配置文件的具体方案的介绍,望你浏览完下面的文章会有所收获. pytho ...

  2. 转:python webdriver API 之设置等待时间

    有时候为了保证脚本运行的稳定性,需要脚本中添加等待时间.sleep(): 设置固定休眠时间. python 的 time 包提供了休眠方法 sleep() , 导入 time 包后就可以使用 slee ...

  3. 转:python webdriver API 之下载文件

    webdriver 允许我们设置默认的文件下载路径.也就是说文件会自动下载并且存在设置的那个目录中.要想下载文件,首选要先确定你所要下载的文件的类型.要识别自动文件的下载类型可以使用 curl ,如图 ...

  4. 转:python webdriver API 之操作测试对象

    一般来说,所有有趣的操作与页面交互都将通过 WebElement 接口,包括上一节中介绍的对象定位,以及本节中需要介绍的常对象操作.webdriver 中比较常用的操作元素的方法有下面几个: cle ...

  5. 转:python webdriver API 之cookie 处理

    有时候我们需要验证浏览器中是否存在某个 cookie,因为基于真实的 cookie 的测试是无法通过白盒和集成测试完成的.webdriver 可以读取.添加和删除 cookie 信息.webdrive ...

  6. 转:python webdriver API 之简单对象的定位

    对象(元素)的定位和操作是自动化测试的核心部分,其中操作又是建立在定位的基础上的,因此元素定位就显得非常重要. (本书中用到的对象与元素同为一个事物)一个对象就像是一个人,他会有各种的特征(属性) , ...

  7. 转:python webdriver API 之 验证码问题

    对于 web 应用来说,大部分的系统在用户登录时都要求用户输入验证码,验证码的类型的很多,有字母数字的,有汉字的,甚至还要用户输入一条算术题的答案的,对于系统来说使用验证码可以有效果的防止采用机器猜测 ...

  8. 转:python webdriver API 之浏览器的操作

    1.1.浏览器最大化在统一的浏览器大小下运行用例,可以比较容易的跟一些基于图像比对的工具进行结合,提升测试的灵活性及普遍适用性.比如可以跟 sikuli 结合,使用 sikuli 操作 flash.# ...

  9. 转:python webdriver API 之调用 JavaScript

    当 webdriver 遇到没法完成的操作时,笔者可以考虑借用 JavaScript 来完成,比下下面的例子,通过 JavaScript 来隐藏页面上的元素.除了完成 webdriver 无法完成的操 ...

  10. 转:python webdriver API 之alert/confirm/prompt 处理

    webdriver 中处理 JavaScript 所生成的 alert.confirm 以及 prompt 是很简单的.具体思路是使用switch_to.alert()方法定位到 alert/conf ...

随机推荐

  1. 生存分析(survival analysis)

    一.生存分析(survival analysis)的定义 生存分析:对一个或多个非负随机变量进行统计推断,研究生存现象和响应时间数据及其统计规律的一门学科. 生存分析:既考虑结果又考虑生存时间的一种统 ...

  2. [分布式系统学习]阅读笔记 Distributed systems for fun and profit 之四 Replication 拷贝

    阅读http://book.mixu.net/distsys/replication.html的笔记,是本系列的第四章 拷贝其实是一组通信问题,为一些子问题,例如选举,失灵检测,一致性和原子广播提供了 ...

  3. 二步实现 远程连接 阿里云SqlServer 2012 数据库服务器

    前言:在使用 阿里云 上的一些产品时,遇到不少坑. 安装IIS 时,遇到 因买的配置过低,虚拟内存不足,而导致 IIS 总是安装失败: 现在 在上面安装了个 Sql Sever 2012,远程老是 不 ...

  4. 地址转换函数:inet_aton & inet_ntoa & inet_addr和inet_pton & inet_ntop

    在Unix网络编程中,我们常用到地址转换函数,它将ASCII字符串(如"206.62.226.33")与网络字节序的二进制值(这个值保存在套接口地址结构中)间进行地址的转换. 1. ...

  5. HTML/css之弹性布局

    1.flex 弹性布局 产生的比较晚 目前在移动网页开发中可以使用 而且逐渐成为主流. 在桌面网页开发中,使用的比较少 (主要是桌面浏览器的兼容性问题更加严重) 开启方法: 在容器标签上,加上disp ...

  6. 反正切函数atan与atan2的区别

    atan 和 atan2 都是求反正切函数,如:有两个点 point(x1,y1), 和 point(x2,y2); 那么这两个点形成的斜率的角度计算方法分别是: float angle = atan ...

  7. Ubuntu 下 kdevelop下 怎么向主函数传递参数

    1.打开工程 2.点击窗口上的运行”--“配置启动器” 3.左栏选择要传递参数的工程名,在参数一栏中,输入参数“ubuntu.png”,再输入“工作目录”.点击OK,运行就可以了.

  8. 畅通工程 HDU - 1863 最小生成树模板

    两个模板: kruskal #include<stdio.h> #include<queue> #include<algorithm> #include<io ...

  9. Oracle体系结构之oracle密码文件管理

    密码文件 密码文件作用: 密码文件用于dba用户的登录认证. dba用户:具备sysdba和sysoper权限的用户,即oracle的sys和system用户. 本地登录: 1)操作系统认证: [or ...

  10. Python:lambda表达式(匿名函数)

    lambda表达式: 通常是在需要一个函数,但是又不想费神去命名一个函数的场合下使用,也就是指匿名函数. 当我们在传入函数时,有些时候,不需要显式地定义函数,直接传入匿名函数更方便. 在Python中 ...