This article will introduce how to encapsulate several commonly used webdriver methods into a class written by yourself. This encapsulation process is called secondary encapsulation of Selenium methods. We encapsulate the methods of opening the site, forwarding and rewinding the browser, closing and exiting the browser into a newly written class.
We create two new packages and two .py files in PyCharm according to the following hierarchy:
In the picture above, baidu_search.py is the python file where we write the test script, and the specific test code is written in this file. The basepage.py file under the package test1 is newly created by the secondary encapsulation selenium method we introduced this time. It is mentioned here that the default rule in python is that the package name and file name are all lowercase, the first letter of the class name is uppercase, the function name is lowercase, and multiple letters are separated by underscores. We try to abide by this unwritten agreement.
Let's take a look at the content of basepage.py:
- # coding=utf-8
- class BasePage(object):
- """
- Mainly to encapsulate several commonly used Selenium methods into the BasePage class, we demonstrate the following methods here
- back()
- forward()
- get()
- quit()
- """
- def __init__(self, driver):
- """
- Write a constructor with one parameter driver
- :param driver:
- """
- self.driver = driver
- def back(self):
- """
- browser back button
- :param none:
- """
- self.driver.back()
- def forward(self):
- """
- browser forward button
- :param none:
- """
- self.driver.forward()
- def open_url(self, url):
- """
- open url site
- :param url:
- """
- self.driver.get(url)
- def quit_browser(self):
- """
- Close and stop the browser service
- :param none:
- """
- self.driver.quit()
Next, let's see how to call our own encapsulated method in our script file.
The content of baidu_search.py is as follows:
- # coding=utf-8
- import time
- from selenium import webdriver
- from test1.basepage import BasePage
- class BaiduSearch(object):
- driver = webdriver.Chrome()
- driver.maximize_window()
- driver.implicitly_wait(10)
- basepage = BasePage(driver)
- def open_baidu(self):
- self.basepage.open_url("https://www.baidu.com")
- time.sleep(1)
- def test_search(self):
- self.driver.find_element_by_id('kw').send_keys("Selenium")
- time.sleep(1)
- self.basepage.back()
- self.basepage.forward()
- self.basepage.quit_browser()
- baidu = BaiduSearch()
- baidu.open_baidu ()
- baidu.test_search()
The few lines of code in self.basepage above are to call our own encapsulated method to perform related webdriver operations. This is just a simple encapsulation introduction. Later, we will introduce string cutting, and we will introduce the secondary encapsulation Selenium method again. For example, we will encapsulate the eight find_element methods into one method.
For more in-depth understanding and communication, please add QQ group: 49044146