General-purpose scripting language Python web automation

web automation scripts have part of the code can learn from, we only need to migrate to the current framework of this project, modify some parameters. Class such as logging, driver objects, the basic element operation.

To the mall project as an example, the following is the relevant code.

base package (containing logs, driver objects, page elements operating):

Page elements operating (base.py):

Time Import 
from SLEEP Time Import

Import Page
from selenium.webdriver.support.wait Import WebDriverWait
from base.get_logger Import GetLogger


# log log is acquired
log GetLogger = () get_logger ().


class Base:

DEF the __init __ (Self, Driver):
log .info ( "[base]: Getting initializing driver objects: {}." the format (driver))
self.driver = driver

# lookup method of packaging elements
DEF base_find (Self, LOC, timeout = 30, poll = 0.5):
log .info ( "[base]: positioning are: {} elements positioned default timeout is: {}." the format (LOC, timeout))
# wait to find using the display element
return WebDriverWait (self.driver,
timeout = timeout,
= poll poll_frequency) .until (the lambda X: x.find_element (* LOC))

# Click method of packaging elements
DEF base_click (Self, LOC):
log.info ( "[Base]: being: {} implement element click event" .format (LOC))
self.base_find (LOC) .click ()

# input element encapsulation method
DEF base_input (Self, LOC, value):
# Get element
EL = self.base_find (LOC)
# Clear
log.info ( "[ Base]: being: empty implement ".format (loc)) {} element
el.clear ()
# input
el.send_keys (value)

# text information acquisition method of packaging
DEF base_get_text (Self, LOC):
log.info (" [Base]: Getting: {element} text value ".format (LOC))
return self.base_find (LOC) .text

# encapsulation method of theme
base_get_image DEF (Self):
log.info ( "[Base]: Error asserted, call theme")
self.driver.get_screenshot_as_file (.format (The time.strftime ( "% Y_%" ../ Image / PNG {}. " D%%% H_ m_Low of M_% S ")))

# determines whether there is a method of packaging element
DEF base_element_is_exist (Self, LOC):
the try:
self.base_find (LOC, timeout = 2)
log.info (" [Base]: { } element lookup is successful, there is a page ".format (LOC))
return True # represents the element is present
the except:
log.info (" [Base]: {} element lookup fails, there is no current page ".format (LOC))
return False # represents the element does not exist

# Back Home (page shopping cart, orders, payments) need to use this method
DEF base_index (Self):
SLEEP (2)
self.driver.get (page.URL)

# switch frame form method
base_switch_frame DEF (Self, name):
self.driver.switch_to.frame (name)

# back to the default directory method
DEF base_default_content (Self):
self.driver.switch_to.default_content ()

# to switch between windows Called by
def base_switch_to_window (self , title):
log.info ( "title is being performed handover: {} window" .format (title))
self.driver.switch_to.window (self.base_get_title_handle (title))

# Gets the title page handle method
def base_get_title_handle (Self, title):
# get the current page all the Handles
for handle in self.driver.window_handles:
log.info ( "being traversed handles: {} -> {} ". format (handle, self.driver.window_handles ))
# switch handle
self.driver.switch_to.window (handle)
log.info ( "handover: {} window" .format (handle))
# Get the current page title and determines whether the designated parameter is equal title
log.info ( "Analyzing current page title: { } is equal to a specified title: {} "format (self.driver.title, title)).
iF self.driver.title == title:
!. log.info (" condition is satisfied return the current handle {} "format (handle ))
# returns the handle
return handle

Driver objects (get_driver.py):
webdriver the Selenium Import from 
Import Page


class getDriver:
Driver = None

# Gets Driver
@classmethod
DEF get_driver (CLS):
IF cls.driver IS None:
# Gets Driver
cls.driver = webdriver.Firefox ()
# maximize browser
cls.driver .maximize_window ()
# open url
cls.driver.get (page.URL)
# returns Driver
return cls.driver

# close Driver
@classmethod
DEF quit_driver (CLS):
IF cls.driver:
cls.driver.quit ()
# must be set No operation
cls.driver = None

the __name__ == IF '__main__':
getDriver () quit_driver ().

log objects (get_logger.py):
logging.handlers Import 


class GetLogger:

logger = None
# outermost running
# filename = "./log/xxxx.log"
# get logger
@classmethod
DEF get_logger (CLS):
# If the logger is empty
if cls.logger is None:
# get logger
cls.logger = logging.getLogger ()
# set default logging level
cls.logger.setLevel (logging.info)
# Gets processor console
SH = logging.StreamHandler ()
# get handle files (time)
TH logging.handlers.TimedRotatingFileHandler = (filename = "../ log / xxxx.log",
When = "Midnight",
interval The =. 1,
BACKUPCOUNT = 30,
encoding = "UTF-. 8")
# Get formatter
fm = "% (asctime) s % (levelname) s [% (name) s] [% (filename) s (% (funcName ) S:% (lineno) D] -% (Message) S "
FMT = logging.Formatter (FM)
# the format setting processor
sh.setFormatter (FMT)
th.setFormatter (FMT)
# to add processors to log viewer
cls.logger.addHandler (SH)
cls.logger.addHandler (TH)
# returns the logger
return cls.logger

defined test suites (run_main.py placed directly under the project directory):
Leader packet # 
Import the unittest
Import Time
from tool.HTMLTestRunner Import HTMLTestRunner


# scripts defined in the test suite
# = unittest.defaultTestLoader.discover Suite ( "./")
# outermost running
suite = unittest.defaultTestLoader.discover ( ". / scripts ")
# report Generator directory and file name
dir_path =" ./report/{}.html".format(time.strftime("%Y_%m_%d% H_% M_% S "))
# get file stream and calls run run
with Open (dir_path, "wb") AS f:
HTMLTestRunner. (Stream = f, title = "Tpshop Mall automated testing report", description = "operating system: win7") run (suite)

in the kit ( tools) files stored HTMLTestRunner.py

These are the Python scripting language commonly used code in web automation, on-demand use.

Guess you like

Origin www.cnblogs.com/ray-mr-huang/p/11526426.html