selenium base
Introduction to selenium
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
WebDriver
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
Python
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 driver.get("https://www.baidu.com") # Get the current URL driver.current_url # Back Press the browser's back button: driver.back() # Forward Press the forward key of the browser: driver.forward() # Refresh the current page: driver.refresh() # Get Title driver.title
Windows and Tabs
# Get the window handle of the current window driver.current_window_handle # Open a new tab and switch to a new tab driver.switch_to.new_window('tab') # Open a new window and switch to a new one driver.switch_to.new_window('window') #Close tab or window driver.close() #Cut back to the previous tab page or window driver.switch_to.window(original_window)
Switch windows or tabs (often asked during interviews)
import time from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # Start Driver with webdriver.Chrome() as driver: # Open Web Address driver.get("https://www.baidu.com") # 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]') topSearch.click() new_window = driver.current_window_handle # Waiting for a new window or tab wait.until(EC.number_of_windows_to_be(2)) # Switch back to the original label time.sleep(2) driver.switch_to.window(original_window) time.sleep(1) # Switch back to the new label driver.switch_to.window(new_window) time.sleep(2)
iframe problem
Define an iframe page
<div id="modal"> <iframe id="buttonframe"name="myframe" src="https://cn.bing.com/" width="800" height="1200"> </iframe> </div>
Enter iframe to manipulate elements within iframe
import time from selenium import webdriver from selenium.webdriver.common.by import By driver = webdriver.Chrome() # Open iframe page driver.get("file://D:/lesson/niu_exame/seleniumTest/iframe.html") # Find the element where iframe is located iframe = driver.find_element(By.CSS_SELECTOR, "#modal > iframe") # Switch to the selected iframe driver.switch_to.frame(iframe) searchKeyword = driver.find_element(By.ID, "sb_form_q") searchKeyword.send_keys("Test Small White Go") time.sleep(2) driver.quit()
Leave iframe
# Cut back to default content driver.switch_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 driver.maximize_window() # minimize windows driver.minimize_window()
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. :Args: - id\_ - The id of the elements to be found. :Returns: - list of WebElement - a list with elements if any was found. An empty list if not :Usage: 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.
driver.implicitly_wait(10)
Bounce window handling
Test Page, Pop-up Test Page.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Bounce window test</title> </head> <body> <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> </body> </html>
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() time.sleep(1) # 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 print(text) # Click on the confirmation button of the pop-up window time.sleep(1) alert.accept() time.sleep(1)
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 print(text) # Click on the pop-up window cancel button time.sleep(1) alert.dismiss() time.sleep(1)
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 print(text) # Send Text alert.send_keys("xxdfasf") # Click on the confirmation button of the pop-up window time.sleep(2) alert.accept() time.sleep(1)
Execute JavaScript scripts
# Modify 12306 first page date via JavaScript class TestActionChains: def setup(self): self.driver = webdriver.Chrome() def teardown(self): self.driver.quit() def test_12306(self): self.driver.get("https://www.12306.cn/index/") 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") print(el.get_property("value")) sleep(2)