Python webdriver api-Read, set configuration file

Source: Internet
Author: User

File structure:

Db.ini configuration file for placing DB information

file [Gloryroad] is section information

The dbname below is the option information

Uiobjectmap.ini placing configuration information for accessing the Web

Configure the XPath element information used-to achieve separation of data and programs

The first step reads the configuration file

Place the configuration file in the directory where the current script is located

#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 class

Cf.read (ConfigFilePath) #实例化后, read, spell full path

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

Added print __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

Debug yourself:

#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 class

Cf.read (ConfigFilePath) #实例化后, read, spell full path

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

Encapsulation into functions

#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

Modify:

#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 '

The second step how to split the configuration file specify browser, section (site name), and element name (element_name)

Uiobjectmap.ini:

[Sogou]

Searchbox=id>query

Searchbutton=id>stb

Script:

#encoding =utf-8

From Selenium.webdriver.support.ui import webdriverwait

Import Configparser

Import OS

From selenium import Webdriver

Class Objectmap (object):

def __init__ (self): #这里把文件路径写死了, you can pass the path as a parameter in the package

# Gets the absolute path to the configuration file where the page element is positioned and the location expression is placed

# Os.path.abspath (__file__) indicates the path directory where the current file is located

Self.uiobjmappath = Os.path.dirname (Os.path.abspath (__file__)) \

+ "\\UiObjectMap.ini"

Print Self.uiobjmappath

def getelementobject (self, driver, Websitename, elementname):

Try

# Create an instance of a read configuration file

CF = Configparser.configparser ()

# Load configuration file contents into memory

Cf.read (Self.uiobjmappath)

# Gets the location of the page elements in the configuration file according to section and option and

# Locate the string that consists of the expression and use the ">" Split

Locators = Cf.get (Websitename, elementname). Split (">")

# Get the Positioning method

Locatormethod = Locators[0]

# Get positional expressions

Locatorexpression = locators[1]

Print Locatormethod, locatorexpression

# get page elements by displaying wait methods

element = webdriverwait (driver, ten). Until (lambda x: \

X.find_element (Locatormethod, locatorexpression))

Except Exception, E:

Raise E

Else

# when the page element is found, return the page element object to the caller

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") >

The third step combines the use of Sogou to click 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):

# Gets the absolute path to the configuration file where the page element is positioned and the location expression is placed

# Os.path.abspath (__file__) indicates the path directory where the current file is located

Self.uiobjmappath = Os.path.dirname (Os.path.abspath (__file__)) \

+ "\\UiObjectMap.ini"

Print Self.uiobjmappath

def getelementobject (self, driver, Websitename, elementname):

Try

# Create an instance of a read configuration file

CF = Configparser.configparser ()

# Load configuration file contents into memory

Cf.read (Self.uiobjmappath)

# Gets the location of the page elements in the configuration file according to section and option and

# Locate the string that consists of the expression and use the ">" Split

Locators = Cf.get (Websitename, elementname). Split (">")

# Get the Positioning method

Locatormethod = Locators[0]

# Get positional expressions

Locatorexpression = locators[1]

Print Locatormethod, locatorexpression

# get page elements by displaying wait methods

element = webdriverwait (driver, ten). Until (lambda x: \

X.find_element (Locatormethod, locatorexpression))

Except Exception, E:

Raise E

Else

# when the page element is found, return the page element object to the caller

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

Script:

#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 ()

# launch Firefox browser

Self.driver = Webdriver. Firefox (Executable_path = "C:\\geckodriver")

def testsogousearch (self):

url = "Http://www.sogou.com"

# Visit Sogou homepage

Self.driver.get (URL)

Try

# Find page Search input box

SearchBox = self.obj.getelementobject\

(Self.driver, "Sogou", "SearchBox")

# enter "Webdriver" in the Search input box found

Searchbox.send_keys (U "webdriver Practical Treasure")

# Find Search button

SearchButton = self.obj.getelementobject\

(Self.driver, "Sogou", "SearchButton")

# Click the search button found

Searchbutton.click ()

# wait 2 seconds for page load to complete

Time.sleep (2)

# assertion that the keyword "Wu Xiaohua" appears in the page source code as expected

Self.asserttrue (U "Wu Xiaohua" in Self.driver.page_source, "Assert error!")

Except Exception, E:

# Print Exception stack information

Print Traceback.print_exc ()

def tearDown (self):

# Quit IE browser

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-Read, set configuration file

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.