文件结构:

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. spring-boot 学习笔记一

    参考博客:https://www.cnblogs.com/ityouknow/p/5662753.html 1.构建项目: 访问http://start.spring.io/,下载demo: 下载解压 ...

  2. 【转】常用html转义符,JavaScript转义符

    HTML字符实体(Character Entities),转义字符串(Escape Sequence) 为什么要用转义字符串? HTML中<,>,&等有特殊含义(<,> ...

  3. Git - Pull Request工作流

    Pull Requests是Bitbucket上方便开发者之间协作的功能.提供了一个用户友好的Web界面,在集成提交的变更到正式项目前可以对变更进行讨论. 开发者向团队成员通知功能开发已经完成,Pul ...

  4. Pointer Lock

    Pointer Lock API 指针锁定(以前叫做 鼠标锁定) 提供了一种输入方法,这种方法是基于鼠标随着时间推移的运动的(也就是说,deltas),而不仅是鼠标光标的绝对位置.通过它可以访问原始的 ...

  5. hdu2222 Keywords Search【AC自动机】

    Keywords Search Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others ...

  6. poj3417Network【LCA】【树形DP】

    Yixght is a manager of the company called SzqNetwork(SN). Now she's very worried because she has jus ...

  7. POJ_3616_Milking Time

    Milking Time Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 10841   Accepted: 4564 Des ...

  8. Docker基本命令与使用 —— Dockerfile指令与构建(三)

    一.Dockerfile指令上 1.指令格式 # Comment 注释, 以#开头 INSTRUCTION argument 以大写的指令+参数 #First Dockerfile 注释 FROM u ...

  9. createrepo local http yum

    https://www.jianshu.com/p/59ca879584a1   repodata作为软件的仓库,其目录下有四个必要文件:filelists.xml.[gz],other.xml.[g ...

  10. CentOs7 安装最新版的Git

    最近打算研究下Git并投入是用,当然要从安装开始了. 服务器的系统是CenterOs7,这个系统和之前的版本还些使用的不同,慢慢习惯吧. 安装方法有两种: 一.yum命令安装,此方法简单,并且会自动安 ...