[Selenium automated testing] How to locate page elements and how to operate page elements

selenium element positioning

There are 8 ways for selenium to locate elements.

fild_element(by,value): by indicates the positioning method used, and the positioning method can refer to the By class. value represents the value, for example: locate according to id

By.ID, value=value of the id attribute. This method returns the element object, and the return value is as follows:

<selenium.webdriver.remote.webelement.WebElement (session="b9c957076ccceb820ad3b873f1292d35", element="f5a68c75-fa74-4613-809a-cda1b3198d94")>

This return result shows that: the return value is an object of the WebElement class, and when the element uses the method, the method of the WebElement class should be called

The positioning method provided by the By class

  1. By.ID: Locate elements based on the value of the tag’s id attribute

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    
    driver = webdriver. Chrome()
    
    driver.get("https://www.baidu.com")
    
    driver.find_element(By.ID,'kw').send_keys('hello python')
    

  2. By.NAME: locate elements according to the value of the tag’s name attribute

    from selenium import webdriver
    driver = webdriver. Firefox()
    driver.get('https://www.baidu.com')
    driver.find_element(By.NAME,'wd').send_keys('Baidu')
    

  3. By.CLASS_NAME: Locate elements according to the class attribute value, you need to pay attention, try not to use class to locate, because in a page, there are often multiple elements with the same class attribute value, so when locating, if there are multiple attributes with the same value element, the first element is automatically positioned.

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    
    
    driver = webdriver. Chrome()
    
    driver.get("https://www.baidu.com")
    
    
    driver.find_element(By.CLASS_NAME,'s_ipt').send_keys('hello python')
    

  4. By.LINK_TEXT: locate elements based on hyperlink text content

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    driver = webdriver. Chrome()
    driver.get('https://www.baidu.com')
    driver.find_element(By.LINK_TEXT,'News').click()
    

  5. By.PARTIAL_LINK_TEXT: Locate elements based on partial link text content

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    driver = webdriver. Chrome()
    driver.get('https://www.baidu.com')
    driver.find_element(By.PARTIAL_LINK_TEXT,'hao').click()
    

  6. By.TAG_NAME: locate elements by tag name

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    driver = webdriver. Chrome()
    driver.get('https://www.baidu.com')
    driver.find_element(By.TAG_NAME,'area').click()
    

  7. By.CSS_SELECTOR: Locate elements according to the css selector. If the element you want to locate has no id, no name, no class, tagname is not unique, and it is not a hyperlink. How to position at this time

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    driver = webdriver. Chrome()
    driver.get('https://www.baidu.com')
    driver.find_element(By.CSS_SELECTOR,'#su').click()
    

  8. By.XPATH: locate elements according to the xpath path

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    driver = webdriver. Chrome()
    driver.get('https://www.baidu.com')
    driver.find_element(By.XPATH, '//*[@id="kw"]').click()
    

    Note: xpath has two representations:

    ? 1. Absolute path:

    ? Start from the html tag, go down in order, and go down layer by layer until the target element. The final path formed is the xpath path. If the element has multiple same-level tags (sibling tags), you can add [ after the tag number], the number represents the first label, and the number starts from 1.

    ? Example: From the following html code, locate the input box whose name attribute is input, and the xpath path is expressed as:

    ?/html/body/div/table/tr/td[1]/input

    <!DOCTYPE html>
    <html>
    <head>
    <title>hello</title>
    </head>
    <body>
    <div>
    <table>
    <tr>
    <td>
    <input type="text" name="input">
    </td>
    <td>
    <button>Login</button>
    </td>
    </tr>
    </table>
    
    </div>
    </body>
    </html>
    

    ? 2. Relative path:

    ? When locating from the target element, the unique identifier cannot be confirmed. Start upward from the element until a parent label that can be uniquely located is found, and then locate downward from the parent label. does not start with html.

    ? Example: In this case, if you want to locate the first input tag, use the xpath relative path positioning method:

    ? First: If the target input cannot be uniquely positioned, you can search upwards to see if its parent tag can be uniquely positioned. If not, you can continue to search upwards until you find the div tag with the id of in1, and start from this To position the label downward, first locate the div label “//div[@id=’in1′]”, and then position downward. If you are not sure that the label whose id is in1 is a div, you can use * instead. This path can be expressed as:

    ? 1. //div[@id=’in1′]/table/tr/td[1]/input

    2. //*[@id=’in1′]/table/tr/td[1]/input

    grammar:

    ? //Tag name[@attribute=”attribute value”]

    <!DOCTYPE html>
    <html>
    <head>
    <title>hello</title>
    </head>
    <body>
    <div></div>
    <div></div>
    <div id="in1">
    <table>
    <tr>
    <td>
    <input type="text" name="">
    </td>
    <td>
    <input type="submit" name="">
    </td>
    </tr>
    </table>
    
    </div>
    </body>
    </html>
    

Target method:

? In the firefox browser, place the mouse on the target element, right-click and select “View Element” (Chrome browser is called inspection), and it will display the target element you want to locate in the developer mode.

? On the target element, you can check which attributes the target element has. If there is an id or name attribute, you can use by_id or by_name to locate the element.

If the above method cannot help you locate the element, you can use the css selector method to locate it. On the target element, right click -> copy -> css selector

Among the commonly used element positioning methods, css and xpath are the most commonly used, because these two positioning methods can basically locate all page elements, and you can also use these two methods to realize parent-child element positioning or sibling element positioning.

The difference between css and xpath css is faster than xpath xpath needs to traverse the entire html file

group element positioning

How to use:

The find_elements method is the same as the find_element method.

The difference is that the method returns a set of elements as a list. If you need one of the elements, you can use the following form of the list to get it, or use the for loop to traverse all the elements.

Example:

from selenium import webdriver
from selenium.webdriver.common.by import By


driver = webdriver. Chrome()


driver.get("https://www.baidu.com")



all_a = driver.find_elements(By.TAG_NAME,'a')
# Get the length of the list, then you can know how many elements there are in the a tag
print(len(all_a))

selenium executes JS code

In selenium, js code can be executed directly. The method is execute_script, which receives the js code to be executed. If you need to get the execution result of the js code, in the js code, you need to use return to return

execute_script (js code)

Example:

from selenium import webdriver
from selenium.webdriver.common.by import By

drver = webdriver. Chrome()
drver.get('https://www.baidu.com')

# return indicates that after the element is positioned, return the element information
js = 'return document. getElementById("kw")'
ele = drver. execute_script(js)
print(ele)

Use js code to operate the scroll bar

from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver. Chrome()
driver. maximize_window()

driver.get('https://python.org')

js = 'scrollBy(0,1000)'
driver. execute_script(js)

Modify the attributes of an element

1. In many windows, when an element is clicked, it will jump to a new window. In selenium, it is often necessary to switch windows to continue the operation, so you can use js code to change it to open in the current window.

#coding=utf-8
__author__ = 'jia'
from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver. Chrome()
driver. maximize_window()

driver.get('https://www.baidu.com')


# Find the news hyperlink and delete its target attribute
js = 'document.querySelector("#s-top-left > a:nth-child(1)").removeAttribute("target")'

driver. execute_script(js)
driver.find_element(By.CSS_SELECTOR,'#s-top-left > a:nth-child(1)').click()

2. When dealing with some special operations, for example, in the time control, the time cannot be input, and only the time control can be operated to select the time. This operation is relatively troublesome, so we can use js to change the time input box to input, then You can directly enter the time without operating the time control.

#coding=utf-8
__author__ = 'jia'
from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver. Chrome()
driver. maximize_window()

driver.get('https://www.baidu.com')


# Find the hyperlink of the news and delete its readonlin attribute
js = 'document.querySelector("#s-top-left > a:nth-child(1)").removeAttribute("readonlin")'

driver. execute_script(js)

element operation of selenium

? send_keys (content): enter content into the element

? click(): click on the element

? text: Get the text content in the element and return the text content

? title: Get the title of the current window and return the title

? is_displayed(): Return True if the element is visible, return False if it is invisible, and generate NoSuchElementException if it does not exist.

? current_url: returns the URL address of the current window

window_handles: Get handles of all windows, get all opened windows

current_window_handle: Get the handle of the current window.

clear(): clears the contents of the text box

Wait:

? When doing automated testing, it is inevitable that you will encounter some problems. For example, when you operate an object in a script, the page has not been loaded yet, and your operation statement has been executed, which will cause the script to fail to execute. For such problems, webdriver Provides a wait operation, wait for a certain time, or find the object within a period of time, then continue the operation. Webdriver provides implicit waiting and explicit waiting. Of course, we can also implement mandatory waiting with the help of package modules.

? In order to solve these problems, we can appropriately add waiting time in the script to ensure that the target element can be located.

sleep waiting

? sleep is how many seconds to wait before continuing to execute the following code. To use sleep, you must first import the time module.

Example: In the Baidu page, enter test, click Baidu, you have to wait for a while before you can click on the element

from selenium import webdriver
from time import sleep
driver = webdriver. Firefox()
driver.get('https://www.baidu.com')
driver.find_element_by_id('kw').send_keys('test')
driver.find_element_by_id('su').click()
#Wait for 2 seconds, and then click the following operation
sleep(2)
driver.find_element_by_css_selector('#\31 > h3:nth-child(1) > a:nth-child(1)').click()

Note: sleep is mandatory waiting, you must wait until the waiting time is reached before proceeding to the next step. If the time is set too long, the execution time of the use case will be long, the script execution efficiency will be low, the waiting time will be short, and elements may not be loaded successfully.

Smart waiting:

? Implicitly wait: implicitly_wait

from selenium import webdriver
driver = webdriver. Firefox()
driver.get('https://www.baidu.com')
driver.find_element_by_id('kw').send_keys('test')
driver.find_element_by_id('su').click()
#Smart wait for 30 seconds
driver. implicitly_wait(30)
driver.find_element_by_css_selector('#\31 > h3:nth-child(1) > a:nth-child(1)').click()

The implicit wait of 30 seconds is the total waiting time. During this 30, if the page load is completed at any time, the waiting will no longer continue to wait, and the subsequent operations will be performed directly. implicitly_wait judges whether the page is loaded successfully every 0.5 seconds. If the loading is not completed within 30 seconds, a timeout will occur.

Implicit waits are suitable for use on page load, the entire page is loaded.

Show Waiting:

WebDriverWait

Explicit wait: WebDriverWait()

? In interface operation, if you use wait, you need to know exactly how long to wait. If the time is too short, it is easy to cause timeout and fail to find the operation element. If the time is too long, it is easy to waste time. If sleep is used, it is a global wait. It can cooperate to realize the waiting operation for an element.

Example:

#coding=utf-8
__author__ = 'jia'

'''
show wait:
    Wait for the specified element to be displayed on the page. Unlike implicit wait, implicit wait does not specify the subject of the wait, but takes the entire page as the wait
    object
    Display waiting can be set to wait for the specified page element


'''
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait


driver = webdriver. Chrome()
driver.get("https://www.sina.com.cn")
# Wait for the element "Military" in the page
# 1. Instantiate the WebDriverWait object
wait = WebDriverWait(driver,20)

# Write a function to position an element
# def fun(driver):
# print('waiting for element')
# return driver.find_element(By.LINK_TEXT,'Military')
# call wait method
wait.until(lambda x:x.find_element(By.LINK_TEXT,'Military'))




driver.find_element(By.LINK_TEXT,'Military').click()

2. Use the ec module to implement waiting

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec



driver = webdriver. Chrome()
driver.get("https://www.sina.com.cn")

WebDriverWait(driver,20).until(ec.visibility_of_element_located((By.LINK_TEXT,'Military')))

driver.find_element(By.LINK_TEXT,'Military').click()

WebDriverWait(driver,20).until(ec.visibility_of_element_located((By.LINK_TEXT,’Military’)))

This code needs explanation, WebDriverWait(driver,20).until(ec.visibility_of_element_located((By.LINK_TEXT,’Military’))). Through the text, check whether the military element is visible on the page, and the height and width of the element are not 0. To sum up the meaning of this code is to judge whether the page has military element and it is visible. If it is not completed, it will check every 0.5 seconds by default until it times out after 20 seconds. If it is completed within 20 seconds, continue to execute the following code. Timeout if no content element found within 20 seconds.

expected_conditions

presence_of_all_elements_located() class: expected to check whether at least one element is present on the page. Returns the list of WebElements
visibility_of_any_elements_located() class: expects to check that at least one element is visible on the page. Returns the list of WebElements
visibility_of_all_elements_located() class: Expected to check if all elements are present on the DOM of a page and visible. Used to find elements Once found and visible, returns a list of WebElements
text_to_be_present_in_element() class: Expected to check if the given text is present in the specified element.
text_to_be_present_in_element_value() class: expects to check if a given text locator is present in an element, text
invisibility_of_element_located() class: Used to check whether an element is invisible or not expected to appear on the DOM.
invisibility_of_element() class: Checks whether an element is invisible and expects to appear on the DOM.
element_to_be_clickable() class: checks that the element’s expectation is visible and enabled so you can click it
class staleness_of(): Wait until the element is no longer attached to the DOM. element is the element to wait for. Returns False if the element is still attached to the DOM, true otherwise.
element_to_be_selected() class: The selection checks the selection’s expectations. element is a WebElement object
element_located_to_be_selected() class: Select the desired to be selected element. locator is a tuple of (by, path)
alert_is_present() class: Check if the alter panel appears

If the article is helpful to you, remember to like, bookmark, and pay attention. I will share some dry goods from time to time…