This article is participating in Python Theme Month. See the link for details

If you have ideas or techniques you’d like to share, feel free to leave them in the comments section.

Selenium is used to Set up an Automated Test Project and search airline tickets. , this paper will optimize and reconstruct its code.

Encapsulate element location functions

In Selenium, it is often necessary to reuse some element retrieval methods, because find_element_by_xxx is a little too cumbersome each time.

We can encapsulate some common methods twice and make a simple function out.

from selenium import webdriver
import selenium
from selenium.webdriver.common.action_chains import ActionChains


Get the element by ID
def id(element) :
    return driver.find_element_by_id(element)

Get elements from CSS
def css(element) :
    return driver.find_element_by_css_selector(element)

# fetch by name
def name(element) :
    return driver.find_element_by_name(element)
Copy the code

After adding a few functions, you’re ready to refactor your code. Compare the code before and after the modification as follows.

Other things, such as the find_element_by_xpath method and the driver.execute_script method that executes JS, can be further encapsulated on their own.

Refine functions into separate files

Once the functions are written, but still mixed with all the Python code, they can be distilled into a single file through code layering. For example, you can extract the functions written above into a functions.py file.

Functions provides. Py files

This file is mainly used to write generic functions used in projects, which can be used repeatedly in other files instead of being written repeatedly.

from selenium import webdriver

driver =  webdriver.Firefox()
def id(element) :
    return driver.find_element_by_id(element)

Get elements from CSS
def css(element) :
    return driver.find_element_by_css_selector(element)

def return_driver() :
    return driver
Copy the code

Notice that I’ve also wrapped the driver fetch object as a function. The resulting directory structure is as follows.

In the main_pro.py file, the values need to be imported into the corresponding functions of the module.

from selenium import webdriver
import time
from selenium.webdriver.common.action_chains import ActionChains
from functions import id,css,return_driver

driver = return_driver()
driver.maximize_window()

driver.get('https://flight.tuniu.com/')

# Define the cities of departure and arrival
from_city = "SJZ"
to_city = "SY"
from_date = "2021-01-01"

id("J_FormDepartCity").send_keys(from_city)
time.sleep(2)
driver.find_element_by_xpath("//div[@class='autocomplete-suggestions'][1]/div[1]").click()

id("J_FormDestCity").send_keys(to_city)
time.sleep(2)
driver.find_element_by_xpath("//div[@class='autocomplete-suggestions'][2]/div[2]").click()

Delete the read-only property of the time control
driver.execute_script("document.getElementById('J_FormDepartDate').removeAttribute('readonly')")
# Set time
id("J_FormDepartDate").clear()
id("J_FormDepartDate").send_keys(from_date)

# Click on the other location to clear the floating window
ActionChains(driver).move_by_offset(0.10).click().perform()

# Click the search button
time.sleep(1)
id("J_Search").click()
Copy the code

It’s the same trick, extracting all the generic stuff into functions.py, while main_pro.py keeps only the business logic code.

To learn further, it involves the basic code layer, business code layer, test code layer. This series will not be expanded; snowballing Python will be covered. As the code is written further, it needs to be reconstructed and iterated constantly. The bigger the project is, the more complex the design is needed. Small Demo class projects generally do not need particularly complex levels, mainly because it is unnecessary, and it is difficult to write the code after layers.

Selenium code exception

In addition to being well-structured, projects also require high exception handling capabilities. In Selenium, common exceptions can be found directly at the following web site.

www.selenium.dev/selenium/do…

NoSuchElementException NoSuchElementException NoSuchElementException NoSuchElementException NoSuchElementException NoSuchElementException NoSuchElementException NoSuchElementException

Supplementary knowledgeimplicitly_wait()methods

When Selenium is used to locate web elements, sometimes the page loads slowly, which may be due to the network speed or other reasons. In this case, a waiting time for retrieving elements is required, which was implemented using the Sleep method of the Time module. Selenium also provides a built-in method called IMPLICITly_WAIT that sets a global intelligent wait time for an element, such as 10 seconds, to be fetched. The intelligent wait is equal to 5 seconds, otherwise, wait 10 seconds and not get, will carry out the next calculation or error.

The specific code format is as follows:

Set the global wait time to 10 seconds
driver.implicitly_wait(10)
driver.get('https://flight.tuniu.com/')
Copy the code

Write in the back

Any project is constantly optimized and restructured in the process of writing, so at the beginning of the project with a global perspective to write programs, repeated adjustment in the process, and constantly improve their project control and design ability, this is the best technology.


Blogger ID: Dream eraser, hope you like, comment, favorites.