PO mode - basepa_element.py in the common directory

Keywords: Selenium

Let's first look at what common has.

basepage_element.py and basepage_elements.py encapsulate keyword-driven, single page element and multiple page elements.
config.py Used to judge the environment
contants.py Read directory structure
log.py Encapsulating log files
uploding.py Packaging Page File Upload

Basepage: Keyword encapsulation. Waiting, Finding Elements, Clicking, Inputting, Getting Text, Getting Properties, Window Switching, iframe Switching, Uploading, Selecting
Element operation: wait, search, operation.
Implemented: Every operation in the page, has carried out exception capture, failure screenshot, operation time.
Now encapsulate a base page file

Import packages: according to their own needs

from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import datetime
from PO.Common.log import MyLog
from PO.Common.contants import Open
from PO.Common.uploading import upload

Then name it. First, write out the dominance and page screenshots. Screenshots are performed only when execution fails.

class BasePage:
    def __init__(self, driver):
        self.driver = driver
        '''
        loc:Location parameter input
        img_doc:Screen name
        timeout:How long does dominance wait
        frequency:Display the waiting interval
        path:Path of file upload
        '''
    # waiting time
    def wait_eleVisble(self, loc, img_doc="", timeout=30, frequency=0.5):
        MyLog ().info ("Waiting element visible:{}".format (loc))
        try:
            # start time
            start = datetime.datetime.now ()
            WebDriverWait (self.driver, timeout, frequency).until (EC.visibility_of_element_located (loc))
            # Ending time
            end = datetime.datetime.now ()
            MyLog ().info ("Start waiting time:{},Waiting for the End Time:{},Waiting Together:{}".format (start, end, end - start))
        except:
            MyLog ().info ("Waiting time invalidation")
            # screenshot
            self.save_web_screenshot (img_doc)
            raise
    # Webpage Screenshot
    def save_web_screenshot(self, img_doc):

        now = time.strftime ('%Y-%m-%d %H-%M')
        filename = ("{}_{}.png".format (img_doc, now))

        try:
            self.driver.save_screenshot (Open.screenshots () + '/' + filename)
            MyLog ().info ("The screenshot of the web page was successfully saved in:{}".format (Open.screenshots () + r'/' + filename))
        except:
            MyLog ().info ("Please check that you are positioned correctly.")
            raise

Then add the lookup element and click

from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import datetime
from PO.Common.log import MyLog
from PO.Common.contants import Open
from PO.Common.uploading import upload

class BasePage:
    def __init__(self, driver):
        self.driver = driver
        '''
        loc:Location parameter input
        img_doc:Screen name
        timeout:How long does dominance wait
        frequency:Display the waiting interval
        path:Path of file upload
        '''


    # waiting time
    def wait_eleVisble(self, loc, img_doc="", timeout=30, frequency=0.5):
        MyLog ().info ("Waiting element visible:{}".format (loc))
        try:
            # start time
            start = datetime.datetime.now ()
            WebDriverWait (self.driver, timeout, frequency).until (EC.visibility_of_element_located (loc))
            # Ending time
            end = datetime.datetime.now ()
            MyLog ().info ("Start waiting time:{},Waiting for the End Time:{},Waiting Together:{}".format (start, end, end - start))
        except:
            MyLog ().info ("Waiting time invalidation")
            # screenshot
            self.save_web_screenshot (img_doc)
            raise

    # Find an element
    def get_element(self, loc, img_doc=""):
        MyLog().info ("Location element:{}".format (loc))
        try:
            return self.driver.find_element (*loc)
        except:
            MyLog ().warning ("Failed to find element")
            # screenshot
            self.save_web_screenshot (img_doc)
            raise
    # Click on Elements
    def click_element(self, loc, img_doc=""):
        # Wait for Elements, Find Elements, Click Elements
        self.wait_eleVisble (loc, img_doc)
        ele = self.get_element (loc, img_doc)
        MyLog().info ("Key click elements:{}".format (loc))
        try:
            ele.click ()
        except:
            MyLog().warning ("Failed to click on the element")
            self.save_web_screenshot (img_doc)
            raise
    # Webpage Screenshot
    def save_web_screenshot(self, img_doc):

        now = time.strftime ('%Y-%m-%d %H-%M')
        filename = ("{}_{}.png".format (img_doc, now))
        try:
           self.driver.save_screenshot (Open.screenshots () + '/' + filename)
            MyLog ().info ("The screenshot of the web page was successfully saved in:{}".format (Open.screenshots () + r'/' + filename))
        except:
            MyLog ().info ("Please check that you are positioned correctly.")
            raise

According to their own scenario needs, encapsulation, I am now temporarily using to obtain text values, input text operations, file upload, click operations.
Overall code:

from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import datetime
from PO.Common.log import MyLog
from PO.Common.contants import Open
from PO.Common.uploading import upload




class BasePage:
    def __init__(self, driver):
        self.driver = driver
        '''
        loc:Location parameter input
        img_doc:Screen name
        timeout:How long does dominance wait
        frequency:Display the waiting interval
        path:Path of file upload
        '''


    # waiting time
    def wait_eleVisble(self, loc, img_doc="", timeout=30, frequency=0.5):
        MyLog ().info ("Waiting element visible:{}".format (loc))
        try:
            # start time
            start = datetime.datetime.now ()
            WebDriverWait(self.driver,timeout,frequency).until(EC.visibility_of_element_located (loc))
            # Ending time
            end = datetime.datetime.now ()
            MyLog ().info ("Start waiting time:{},Waiting for the End Time:{},Waiting Together:{}".format (start, end, end - start))
        except:
            MyLog ().info ("Waiting time invalidation")
            # screenshot
            self.save_web_screenshot (img_doc)
            raise

    # Find an element
    def get_element(self, loc, img_doc=""):
        MyLog().info ("Location element:{}".format (loc))
        try:
            return self.driver.find_element (*loc)
        except:
            MyLog ().warning ("Failed to find element")
            # screenshot
            self.save_web_screenshot (img_doc)
            raise
    # Click on Elements
    def click_element(self, loc, img_doc=""):
        # Wait for Elements, Find Elements, Click Elements
        self.wait_eleVisble (loc, img_doc)
        ele = self.get_element (loc, img_doc)
        MyLog().info ("Key click elements:{}".format (loc))
        try:
            ele.click ()
        except:
            MyLog().warning ("Failed to click on the element")
            self.save_web_screenshot (img_doc)
            raise
    #Input text operation
    def text_input_element(self,loc,img_doc="",*args):
        self.wait_eleVisble (loc, img_doc)
        ele = self.get_element (loc, img_doc)
        MyLog().info ("Text input:{}".format (args))
        try:
            ele.clear()
            ele.send_keys(args)
        except:
            MyLog().warning ("Input text value failed")
            self.save_web_screenshot (img_doc)
            raise
    #Getting Text Value
    def text_element(self,loc,img_doc=""):
        self.wait_eleVisble(loc,img_doc)
        ele =self.get_element(loc,img_doc)
        try:
            text = ele.text
            MyLog ().info ("element:{}The text value obtained is:{}".format (loc, text))
            return text
        except:
            MyLog().warning("Failed to get text value")
            self.save_web_screenshot(img_doc)
            raise

    #File upload
    def files_upload_element(self,path,img_doc=""):
        try:
            time.sleep(3)
            upload(path)
            time.sleep(2)
        except:
            MyLog().warning("File path error")
            self.save_web_screenshot(img_doc)
            raise

    # Webpage Screenshot
    def save_web_screenshot(self, img_doc):
        now = time.strftime ('%Y-%m-%d %H-%M')
        filename = ("{}_{}.png".format (img_doc, now))
        try:
            self.driver.save_screenshot (Open.screenshots () + '/' + filename)
            MyLog ().info ("The screenshot of the web page was successfully saved in:{}".format (Open.screenshots () + r'/' + filename))
        except:
            MyLog ().info ("Please check that you are positioned correctly.")
            raise

How to call it? Simple, good: If we write like this, others will not know what we are doing, only know that this thing can be clicked, but we do not find that there are waiting, clicking, searching, logging, screenshots and other operations.
It also saves writing duplicate code every time, such as repeating explicit code, repeating find_xx.click() operation.

from selenium import webdriver
from selenium.webdriver.common.by import By
from PO.Common.basepage_element import BasePage

driver = webdriver.Chrome()
driver.get("http://www.baidu.com")
BasePage(driver).click_element((By.XPATH,'//div[@id="u1"]//a[@name="tj_settingicon"]','Baidu Click Settings')

Posted by y2kbug on Fri, 26 Jul 2019 00:33:47 -0700