Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Automated testing: 8 ways to locate the elements of Selenium pages

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

Shulou(Shulou.com)06/01 Report--

Some time ago, due to the needs of the project, learn Selenium for automatic testing. Now summarize and sort out the methods of element positioning in Selenium, hoping to help some friends who have questions.

Automated test steps:

Location element → operation element → verification operation result → record test result

In the process of automated testing, the test program usually operates the page element step to find the page element of Web, and assigns it to a storage object (WebElement) to operate on the object that stores the page element, such as clicking on the link, typing characters in the input box, etc., to verify whether the element on the page meets the expectations.

Through these three steps, we can complete the operation of a page element, and finding the page element is a very important step. If you can't find the page elements, you can't do it later. The realistic complexity of Web page technology makes it difficult to locate a large number of page elements. There are often people who don't know how to locate.

A complete set of positioning methods

Define a Web page element using the findElement function of the WebDriver object

Use the findElements function to locate multiple elements of a page

Located page elements need to be stored using a WebElement object for later use

The common methods for locating page elements are as follows

An example of Java language implementation of location method

Id locates driver.findElement (By.id ("value of id"))

Name locates driver.findElement (By.name ("value of name"))

All text of the link locates driver.findElement (By.linkText ("all text of the link"))

Partial text of the link locates driver.findElement (By.partialLinkText ("partial text of the link"))

Css method to locate driver.findElement (By.cssSelector ("css expression"))

Xpath method to locate driver.findElement (By.xpath ("xpath expression"))

Class name locates driver.findElement (By.className ("class attribute"))

TagName tag name locates driver.findElement (By.tagName ("tag name"))

Jquery mode Js.executeScript ("return jQuery.find (" jquery expression ")")

How to locate it?

When using selenium webdriver for element positioning, you usually use the findElement or findElements method combined with the By class to return the element handle to locate the element

The findElement () method returns an element, and if it is not found, it throws a different NoElementFindException ()

The findElements () method returns multiple elements. If it is not found, it returns an empty array and does not throw an exception.

How to choose the positioning method?

The strategy is to choose a simple and stable positioning method.

When a page element has an id attribute, try to use id to locate it. If not, choose another location method.

CssSelector is fast, so it is recommended to use it.

Consider linkText or partialLinkText when locating hyperlinks: note, however, that the text changes frequently, so it is not recommended.

Xpath is the most powerful. At that time, the execution was slow, because you need to find the entire DOM, so use it as little as possible. Xpath is used only when there is really no way out.

Here, beginners can learn how to locate elements one by one according to the following examples.

Environmental preparation

First create a hello.html page for the following demonstration

Hello, World!

My look at the cloud home page

User name:

Password:

Region:

Guangzhou

Foshan

Maoming

Xiangfan

Submit

Create a find_location.py file in the same directory and initialize the work

From selenium import webdriver

Import os

# create a Chrome driver instance

Driver = webdriver.Chrome ()

# launch the browser and navigate to the specified URL

In order to overwrite more element positioning here, I have written a local hello.html file myself.

File_path = 'file:///' + os.path.abspath (' hello.html')

Driver.get (file_path)

Element positioning

Positioning through class

Find_element_by_class_name (self, name):

Find_elements_by_class_name (self, name):

# locate the element whose class name is "head_title"

Head_title = driver.find_element_by_class_name ("head_title")

Print (head_title.text)

Positioning through id

Find_element_by_id (self, id_):

Find_elements_by_id (self, id_):

# locate the element whose id is "world"

World = driver.find_element_by_id ("world")

Print (world.text)

Locate through the name attribute

Find_element_by_name (self, name):

Find_elements_by_name (self, name):

# locate the element whose name is "username"

Username = driver.find_element_by_name ("username")

Print (username.get_attribute ("value"))

Locate by marking and signing

Find_element_by_tag_name (self, name):

Find_elements_by_tag_name (self, name):

# locate the element that the label is

Submit_btn = driver.find_element_by_tag_name ("button")

Print (submit_btn.text)

Locate through linked text

Find_element_by_link_text (self, link_text):

Find_element_by_partial_link_text (self, link_text):

# the location link text exactly matches the element of "my look at the cloud home page"

Kancloud = driver.find_element_by_link_text ("my look at Cloud Home")

Print (kancloud.get_attribute ("href"))

# locate the text part of the link that matches the elements of "look at Cloud Home Page"

Kancloud = driver.find_element_by_partial_link_text ("look at Cloud Home")

Print (kancloud.get_attribute ("href"))

Positioning through xpath

Find_element_by_xpath (self, xpath):

Find_elements_by_xpath (self, xpath):

# xpath location, relative path location user name input box

Username = driver.find_element_by_xpath ("/ / body/div/input")

Print (username.get_attribute ("value"))

# xpath location, relative path and attribute are combined to locate the password input box

Password = driver.find_element_by_xpath ("/ / input [@ name='password']")

Print (password.get_attribute ("value"))

# xpath positioning, multiple attributes combined with positioning password input box

Password = driver.find_element_by_xpath ("/ / input [@ name='password'] [@ type='text']")

Print (password.get_attribute ("value"))

Positioning through css selector

Find_element_by_css_selector (self, css_selector):

Find_elements_by_css_selector (self, css_selector):

# css selector, tag + attribute location user name input box

Username = driver.find_element_by_css_selector ("input [name = 'username']")

Print (username.get_attribute ("value"))

# css selector, label + class class name location user name input box

Username = driver.find_element_by_css_selector ("input.user_name")

Print (username.get_attribute ("value"))

# css selector, tag + multiple class class names, locate password input box, be careful not to leave spaces, spaces represent the next level of child elements

Password = driver.find_element_by_css_selector ("input.ptqa.pwd")

Print (password.get_attribute ("value"))

# css selector, id+ multiple class class names, location password input box

Password = driver.find_element_by_css_selector ("# login_form .ptqa.pwd")

Print (password.get_attribute ("value"))

# css selector, multi-level class class name, location password input box

Password = driver.find_element_by_css_selector (".login .ptqa.pwd")

Print (password.get_attribute ("value"))

# css selector, class class name + attribute, location password input box

Password = driver.find_element_by_css_selector (".login .ptqa [name='password']")

Print (password.get_attribute ("value"))

# css selector to locate the password input box according to the parent-child relationship

Password = driver.find_element_by_css_selector ("div [id = 'login_form'] > input [name =' password']")

Print (password.get_attribute ("value"))

# css selector to locate the password input box according to Brotherhood

Password = driver.find_element_by_css_selector ("input [name = 'username'] + input")

Print (password.get_attribute ("value"))

The above methods for locating elements all list two, one of which is find_elements_by_xxx. This method is used when there are multiple elements in the result, such as the option to get the drop-down list below.

# what you get with find_element_by_css_selector is a single element

Mm = driver.find_element_by_class_name ("city") .find_element_by_css_selector ("option [value = 'mm']")

Print (mm.text)

Print ("-" * 20)

# using find_elements_by_css_selector to get the list of element groups

Cities = driver.find_elements_by_css_selector (".city option")

Print (type (cities))

For city in cities:

Print (city.text)

The running result is:

Maoming

-

Guangzhou

Foshan

Maoming

Xiangfan

Universal Ultimate location Grammar

All the above elements locate the results of find_element_by_xxx and find_elements_by_xxx calls, which are actually calling the following two methods, or we can call both methods directly.

Find_element (self, by=By.ID, value=None):

Find_elements (self, by=By.ID, value=None):

Class By (object):

"

Set of supported locator strategies.

"

ID = "id"

XPATH = "xpath"

LINK_TEXT = "link text"

PARTIAL_LINK_TEXT = "partial link text"

NAME = "name"

TAG_NAME = "tag name"

CLASS_NAME = "class name"

CSS_SELECTOR = "css selector"

For example:

From selenium.webdriver.common.by import By

# locate the element whose id is "world" according to id

World = driver.find_element (By.ID, "world")

Print (world.text)

# xpath location, relative path and attribute are combined to locate the password input box

Password = driver.find_element (By.XPATH, "/ / input [@ name='password']")

Print (password.get_attribute ("value"))

# css selector, tag + attribute location user name input box

Username = driver.find_element (By.CSS_SELECTOR, "input [name = 'username']")

Print (username.get_attribute ("value"))

Positioning summary

My favorite positioning method, the priority is id, if there is no id to find class, if class is not easy to locate, find css selector. I think the css selector is the most flexible and powerful way to locate. When using xpath positioning, remember not to use absolute paths, it is best to combine relative paths with attributes.

Pay attention to 51Testing software testing network, improve it skills, will never be proficient only one step away.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Network Security

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report