python webdriver api-讀取、設定設定檔

來源:互聯網
上載者:User

標籤:abs   ted   imp   parser   exp   inux   載入完成   test   異常   

檔案結構:

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-讀取、設定設定檔

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.