Location>code7788 >text

selenium review - principles + basic usage

Popularity:580 ℃/2024-08-05 23:09:40

synopsis

1. What it is

selenium is a third-party library for page element positioning, a tool for web automation testing that runs directly in the browser.

2. Principle:

selenium has three roles in the working process, the selenium client, the webdriver and the browser
The selenium client is the interface between the developer and selenium, it sends commands to the webdriver
The browser receives the execution commands from the webdriver and completes the corresponding operations.

positioning of elements

  • Locate by xpathdriver.find_element(, 'element path')
    1. Absolute path (not recommended)
    2、Relative path: start from a qualified element, start with //, must be followed by the label name or(indicates all labels)
# Relative path + index
//from/span[1]
# relative path + attribute positioning: //tag name[@attribute name1 = 'attribute value']
//input[@autocomplete = 'off']
# Relative path + text positioning: //tag name[text() = 'x']
//span[text() = 'search by image']
  • Positioning via CSSdriver.find_element(By.CSS_SELECTOR, '')
# 1. Use # for the id attribute
driver.find_element(By.CSS_SELECTOR, "#user")
# 2. to represent the class attribute driver.find_element(By.CSS_SELECTOR, '.tel')
# 3. Locate by attribute
[attribute = value]
# 4. Locating by partial attribute value
# Element by attribute value starting at value
[attribute^ = value]
# Find elements with value in the attribute's value.
[attribute* = value]
# Find elements with attribute values ending in value
[attribute$ = value]
# 5. Combination selector
##1. descendant selector: space
# Indicates all descendant elements within the div tag, children, grandchildren, great-grandchildren, etc.
div span
## 2. descendant selector: >
# Indicates a subset of span elements within div (subclasses only)
div>span
## 3. Sibling selector: ~
# Indicates that the element that is a brother to the first div and comes after the first div
div~div
## 4. child element a:nth-child(1)
## Select the element in the nth <a>.
a:nth-child(1)
  • Localization by ID (ID attribute)
    driver.find_element(, "value")
  • Localization by class-name (class attribute)
    driver.find_element(By.CLASS_NAME, "value")
  • Locate by tag-name (tag_name)
    driver.find_element(By.TAG_NAME, "input")
  • Positioning via link_text (hyperlink)
    driver.find_element(By.LINK_TEXT, "login")
  • Positioning by partial_link (hyperlink)
    driver.find_element(By.PARTIAL_LINK_TEXT, "value")

Browser Operation

1. Initialize the browser object
from import Chrome
# Create a browser object and open an empty page
browser = Chrome()
2. Access to specified web pages
from selenium import webdriver
# Initialize the browser to chrome
browser = ()
# Access the Baidu home page
(url)
3. Setting the browser size
from selenium import webdriver
import time
browser = ()
(url)
# Setting the browser to full screen
browser.maximize_window()
(2)
# Set the resolution to500*500
browser.set_window_size(500, 500)
# Close Browser
()
4. Refresh the page
from selenium import webdriver

browser = ()
browser.maximize_window()
(url)

# refresh page
try:
  ()
except Exception as e:
  print("refresh failure")
5. Get the basic properties of the page
# Title of the page
print()
# Get the URL of the current page
print()
# Get the name of the browser
print()
# Get the browser's page source
print(browser.page_sourse)
6. Browser page forward and backward
browser = ()
browser.maximize_window()
("")
(2)

("")
(2)

# Back to Baidu page
()
(5)
# Forward to Taobao page
()
(5)

Waiting for operation

  • implicitly wait
# Set implicitly wait
driver.implicitly_wait(15)
  • Show Waiting
# Dynamically wait for an event.
# For example: an element can be located, an element can be seen
# Instantiate the wait object
# Set the wait time loc
loc = (, "search-input")
# Constantly locate elements according to set events
# Determine if the element is loaded
ele = WebDriverWait(driver, 10).until(EC.presence_of_element_located(loc))
# Determine if the element is visible
WebDriverWait(driver, 10).until(EC.visibility_of_element_located(loc))
  • stationary wait
sleep()

Page Interactions

1. Browser window switching operations

Get the handle of the current window: current_window_handle
Returns all window handles of the current browser: window_handles
For switching to the corresponding window: switch_to_windows()

from selenium import driver
import time


browser = ()
browser.maximize_window()
("")
# Create a new tab
browser.execute_script('()')
print(browser.current_window_handle)
print()
# Jump to the second tab
borwser.switch_to_window(browser.window_handles[1])
("")
(5)
# Go back to the first tab and open Taobao
browser.switch_to_window(browser.window_handle[0])
("")
2. html nested iframe operation
# Cut to iframe
# Switch with ID
driver.switch_to_frame("idframe2")
# Switch with name
driver.switch_to_name("myframe2")
# Switch with index, starting from 0
driver.switch_to_frame(1)
3. Drop-down box option processing

Involves the select module

from selenium import webdriver
from import Select
from import By
import time

url = ""
browser = ()
browser.maximize_window()
(url)

# Get the corresponding label
select_tag = browser.find_element(, "lady-killer")
# Selection based on index value
Select(select_tag).select_by_index("2")
# according tovaluecarry out a selection
Select(select_tag).select_by_value("grass")
# according to文本值carry out a selection
Select(select_tag).select_by_visible_text("talent scout")
(5)

Mouse operation

from .action_chains import ActionChains


# Click actions
from .action_chains import ActionChains
from selenium import webdriver
from import By
import time

browser = ()
(r'')
(2)

# Locate the element to right-click on, in this case the news link
click_tag = browser.find_element(By.LINK_TEXT, 'news')
click_tag.click()
# ActionChains(browser): calls the ActionChains() class with the browser driver browser as an argument
# context_click(right_click): simulates a double-click on the mouse, passing in the specified element positioning as a parameter
# perform(): performs all the actions stored in ActionChains(), which can be thought of as a series of actions before execution
# double-click
# Locate the element to be double-clicked
double_click = browser.find_element(By.CSS_SELECTOR, '.accessibility-icon')
ActionChains(browser).double_click(double_click).perfrom()
# right_click
right_click = browser.find_element(By.CSS_SELECTOR, '.accessibility-icon')
ActionChains(browser).context_click(right_click).preform()
# Drag and drop
# Start position
source = browser.find_element(By.CSS_SELECTOR, "#draggable")
# End position
target = browser.find_element(By.CSS_SELECTOR, "#droppable")
# Execute the drag and drop
ActionChains(browser).drag_and_drop(source, target).perform()
# Hover
# Locate the hover position
move = browser.find_element(, "s-usersetting-top")
# Perform the hover action
ActionChains(browser).move_to_element(move).preform()

key operation

from import Keys
# Emulate keys on the keyboard via the send_keys() method.

JS operations

CAPTCHA handling

unittest operation

The unittest framework is a unit testing framework that comes with python and allows for automated testing
unittest + selenium => webui automated testing
unittest + requests => interface automation test
unittest + appnium = mobile app automation testing

1. unittest core elements
2. Practical application
  • Defining Test Cases
  • testsuit and testrunner

    Instantiate the test suite: suit01 = ()
    Add test method: (TestAdd001("test_01"))
    Instantiate the runner object: run01 = ()
    Running: (suit01)

  • TestLoader

    Instantiating the runner
    Running Test Cases

  • Fixture
methodological
class Test()
  def setUp(self):
    print("...")

  def tearDown(self):
    print("...")
class
class Test():
  @classmethod
  def setUpClass(cls)->None:
    print("...")
  def tearDownClass(cls)->None:
    print("...")
module-level
  • Skipping of use cases
# Skip the test case by using skip before the method
@(condition, "message")
# Or
@("message")
def test(self).
  ...
  ...