selenium base operation

Posted by MattWeet on Sun, 05 Sep 2021 05:10:27 +0200

selenium base

Introduction to selenium

Official Documents

Selenium supports the automation of all major browsers in the market by using WebDriver.Webdriver is an API and protocol that defines a language-neutral interface for controlling the behavior of web browsers.Each browser has a specific WebDriver implementation called a driver.The driver is the component responsible for delegating to the browser and handling communication with Selenium and the browser.

In summary, selenium is used for webUi automation and supports multiple languages and browsers.

selenium architecture

selenium three components


If you start using desktop Web site test automation, you will use WebDriver APIs. WebDriver Use browser automation APIs provided by browser vendors to control browsers and run tests. This is just like real users are operating browsers. Since WebDriver does not require application code to compile its API, it is not intrusive in nature. Therefore, the application you are testing is the same as a real-time push application.

Equivalent to Code Driven Services

Selenium IDE

Selenium IDE (Integrated Development Environment Integrated Development Environment) is a tool for developing Selenium test cases. This is an easy-to-use Chrome and Firefox browser extension and is often the most efficient way to develop test cases. It uses existing Selenium commands to record user actions in the browser.Parameters are determined by the context of the element. This saves development time and is a good way to learn Selenium scripting syntax.

Official own browser plug-in to record scripts and generate code to save development time.

Selenium Grid

Selenium Grid allows you to run test cases on different machines on different platforms. You can control the operation of test cases locally, and when they are triggered, they are executed automatically by the remote end.

When you have developed the WebDriver test, you may need to run it on a combination of multiple browsers and operating systems. This is Grid Where to use it. `

Distributed running Selenium scripts, compatibility testing

Install Selenium Library


You can install Python's Elenium library using pip:

pip install selenium

Install browser drivers

Google Browser Driven Download

Chromium/Chrome download

Download the driver version for the browser version

Once the download is complete, it can be placed directly in the corresponding python directory in the configured path, such as D:\Program Files\Python\Python39

WebDriver Main Operations

Manipulate Browser

# Open Google Browser
from selenium import webdriver
driver = webdriver.Chrome()

# Open Baidu Home Page

# Get the current URL

# Back Press the browser's back button:

# Forward Press the forward key of the browser:

# Refresh the current page:

# Get Title

Windows and Tabs

# Get the window handle of the current window

# Open a new tab and switch to a new tab

# Open a new window and switch to a new one

#Close tab or window

#Cut back to the previous tab page or window

Switch windows or tabs (often asked during interviews)

import time

from selenium import webdriver
from import WebDriverWait
from import expected_conditions as EC

# Start Driver
with webdriver.Chrome() as driver:
    # Open Web Address

    # Set Wait
    wait = WebDriverWait(driver, 10)

    # Stores the ID of the original window
    original_window = driver.current_window_handle

    # Click on Baidu Hotsu News to open a new tab
    topSearch = driver.find_element_by_xpath('//*[@id="hotsearch-content-wrapper"]/li[1]/a/span[2]')
    new_window = driver.current_window_handle

    # Waiting for a new window or tab

    # Switch back to the original label

    # Switch back to the new label

iframe problem

Define an iframe page

    <div id="modal">
        <iframe id="buttonframe"name="myframe" src="" width="800" height="1200">

Enter iframe to manipulate elements within iframe

import time
from selenium import webdriver
from import By

driver = webdriver.Chrome()

# Open iframe page

# Find the element where iframe is located
iframe = driver.find_element(By.CSS_SELECTOR, "#modal > iframe")

# Switch to the selected iframe

searchKeyword = driver.find_element(By.ID, "sb_form_q")
searchKeyword.send_keys("Test Small White Go")


Leave iframe

# Cut back to default content

Window Management

# Get each size separately
width = driver.get_window_size().get("width")
height = driver.get_window_size().get("height")

# Or store dimensions and query them later
size = driver.get_window_size()
width1 = size.get("width")
height1 = size.get("height")

# Set window size
driver.set_window_size(1024, 768) 	

# maximize window

# minimize windows

Element Positioning

class name	Location class Elements whose attributes match the search values (composite class names are not allowed)

css selector	Location CSS Selector Matching Element

id	Location id Element whose attribute matches the search value

name	Location name Element whose attribute matches the search value

link text	Location link text Anchor elements whose visual text exactly matches the search value

partial link text	Location link text An anchor element whose visual text portion matches the search value portion.If multiple elements are matched, only the first element is selected.

tag name	Locate elements whose label name matches the search value

xpath	Location and XPath Elements of expression matching

find_element_by_XX and find_element(By.XX, "") difference

No difference, find_element_by_XX, returns find_element(By.XX, "") method

find_element(By.XX, "") is more suitable for secondary code encapsulation

Partial find_elements_by_id source

    def find_elements_by_id(self, id_):
        Finds multiple elements by id.

         - id\_ - The id of the elements to be found.

         - list of WebElement - a list with elements if any was found.  An
           empty list if not

            elements = driver.find_elements_by_id('foo')
        return self.find_elements(by=By.ID, value=id_)

wait for

Show Waiting

Show Wait is a command-based procedural language available to Selenium customers.They allow your code to pause program execution or freeze threads until the conditions for passing are met.This condition is called at a certain frequency until the wait time-out.This means that as long as a condition returns a false value, it will always try and wait

WebDriverWait(driver, timeout=3).until(some_condition)

Implicit Wait

Implicit wait tells WebDriver to poll the DOM for a while when looking for one or more elements that are not immediately available.The default setting is 0, which means disabled.Once set, implicit wait is set to the life cycle of the session.


Bounce window handling

Test Page, Pop-up Test Page.html

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>Bounce window test</title>
    <button onclick="window.alert('alert Pop-up window test')" id="alert">alert Popup</button><br><br>
    <button onclick="window.confirm('confirm Pop-up window test')" id="confirm">confirm Popup</button><br><br>
    <button onclick="window.prompt('prompt Pop-up window test','Test Small White Go')" id="prompt">prompt Popup</button>

Alerts Warning Box

with webdriver.Chrome() as driver:
    driver.get("file://D:/lesson/niu_exame/seleniumTest/pop-up test page.html")
    # Click the alert pop-up button
    driver.find_element(By.ID, "alert").click()

    # Wait for the pop-up window to appear
    alert = WebDriverWait(driver, timeout=3).until(expected_conditions.alert_is_present())

    # Save pop-up window text
    text = alert.text

    # Click on the confirmation button of the pop-up window

Confirm Confirmation Box

with webdriver.Chrome() as driver:
    driver.get("file://D:/lesson/niu_exame/seleniumTest/pop-up test page.html")    
    # Click the confirm pop-up button
    driver.find_element(By.ID, "confirm").click()

    # Wait for the pop-up window to appear
    WebDriverWait(driver, timeout=3).until(expected_conditions.alert_is_present())

    # Second method of saving pop-up window variables
    alert = driver.switch_to.alert

    # Save pop-up window text
    text = alert.text

    # Click on the pop-up window cancel button

Prompt prompt box

with webdriver.Chrome() as driver:
    driver.get("file://D:/lesson/niu_exame/seleniumTest/pop-up test page.html")

    # Click the prompt pop-up button
    driver.find_element(By.ID, "prompt").click()

    # Wait for the pop-up window to appear
    WebDriverWait(driver, timeout=3).until(expected_conditions.alert_is_present())

    # Third way to save pop-up variables
    alert = Alert(driver)

    # Save pop-up window text
    text = alert.text

    # Send Text

    # Click on the confirmation button of the pop-up window

Execute JavaScript scripts

# Modify 12306 first page date via JavaScript
class TestActionChains:
    def setup(self):
        self.driver = webdriver.Chrome()

    def teardown(self):

    def test_12306(self):
            self.driver.execute_script("a = document.getElementById('train_date')")
            self.driver.execute_script("a.value = '2021-09-12'")
            el = self.driver.find_element(By.ID, "train_date")

Topics: Python Selenium