python webdriver api-读取、设置配置文件

时间:2022-04-01 16:16:41

文件结构:

db.ini放置db信息的配置文件

文件中[gloryroad]是section信息

下边的dbname等是option信息

UiObjectMap.ini放置访问web的配置信息

python webdriver api-读取、设置配置文件

配置用到的xpath元素信息-做到数据和程序的分离

python webdriver api-读取、设置配置文件

第一步读取配置文件

把配置文件放到当前脚本所在目录下

#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