Summary of how to select elements in Selenium

This is a summary of how to select HTML elements with Selenium's findElement and findElements methods.

I often test non-customizable sites personally (for reasons such as being automatically generated), and I have summarized the patterns I have used mainly for element selection when transitioning to the next screen. ..

The screenshots in each section show the example site above and the elements below with Chrome's validation feature (developer tools). I tried to put it as it is as much as possible, but there are some that have been slightly modified, such as shortening the width for Qiita and deleting the actual data.

1) Search by id attribute

Example that can be searched by id attribute:

image.png

If the desired HTML element has an id attribute, just specify it and search.

driver.findElement(By.id("service_category_cloud_Expert")).click();

All of these sites are easy to test (or rather, you don't need this article).

2) Search by name attribute

Example that can be searched by name attribute:

image.png

The name attribute is also basically unique, so just specify it.

driver.findElement(By.name("Submit")).click();

3) Search by class attribute

Example that can be searched by unique class attribute:

image.png

If it is expected that there is only one desired class attribute, it can be obtained with findElement () as well as the id and name attributes. In this example, it is expected that there is only one "Next" button (btn_next class) on the site, so we get it as it is by specifying the class. If there are multiple elements with the same class, the first one will be returned.

driver.findElement(By.className("btn_next")).click();
// driver.findElements(By.className("btn_next")).get(0).click();Same as

Example of having multiple same class attributes:

image.png

If there are multiple, additional processing is required to get them in the list and find the desired link in them. In this example, the attribute "aria-label" is used to identify the element to click.

List<WebElement> elements = driver.findElements(By.className("mv-tile"));
WebElement targetElement = null;
for (WebElement element: elements ) {
    if (element.getAttribute("aria-label").contains("Publickey")) {
        targetElement = element;
    }
}
targetElement.click(); //If you click in an if statement, an Exception will be thrown if there is an element that does not correspond to the end.

4) Search by title attribute

From here, it will be the pattern specified by xpath.

Example that can be searched by title attribute:

image.png

Search for tags with a specific title as follows. In this example, we are looking for an a tag with the title'Public Report'.

driver.findElement(By.xpath("//a[@title='Public report']")).click();

If the title is long, you can also perform a partial search with contains.

driver.findElement(By.xpath("//a[contains(@title,'Part of a long title')]")).click();

If the title attribute is set, other tags can be searched in the same way. For an input tag with a specific title:

driver.findElement(By.xpath("//input[@title='name']")).sendKeys("Tesuto Ichiro");
driver.findElement(By.xpath("//input[contains(@title,'Part of the title')]")).sendKeys("Text input");

5) Search by value attribute

Example that can be searched by value attribute:

image.png

The value attribute is also searched in combination with the tag as well as the title.

driver.findElement(By.xpath("//input[@value='000200']")).click();

6) Search by alt attribute

Example that can be searched by alt attribute:

image.png

The alt attribute is also searched in combination with the tag. Since alt is often long, I think that partial matching is often used.

driver.findElement(By.xpath("//a[contains(@alt,'Contact Us')]")).click();

Exact match is possible, though not so often.

driver.findElement(By.xpath("//input[@alt=\"Registration\"]")).click();

7) Search by tag

From here, it is a pattern to search by html structure such as tags.

Examples that can be searched by tag:

68747470733a2f2f71696974612d696d616782e706e67.png

The process of getting the elements with the same tag in a list and finding the desired link in them is the same as 3) multiple classes. In this example, it is specified using the "alt" attribute.

List<WebElement> elements = driver.findElements(By.tagName("img"));
WebElement targetElement = null;
for (WebElement element : elements) {
    if (element.getAttribute("alt").equals("In-house business")) {
        targetElement = element;
    }
}
targetElement.click();

In this example, the narrowing condition is alt, so you can also get it by 6) notation of alt attribute. (Depending on the combination of tags and attributes, it is difficult to decide which one to use.)

driver.findElement(By.xpath("//img[@alt=\"In-house business\"]")).click();

Also, if you have only one tag, you can search with findElement, but I think this is rare.

driver.findElement(By.tagName("img")).click();
// driver.findElements(By.tagName("img")).get(0).click();Same as

8) Path specification (table search)

Table search example:

image.png

If the table only has a generic class, get it with the path of the table. In this example, the displayed content contains line breaks and comments, so the indexOf method is used to search for the desired character string.

List<WebElement> tableElements = driver.findElements(By.xpath("//table[@class='table1']/tbody/tr/td/a"));
WebElement targetElement = null;
for(WebElement element : tableElements) {
    if (element.getText().indexOf("PRODUCT002") != -1) {
        targetElement = element;
    }
}
targetElement.click();

9) Path specification (list search)

List search example:

image.png

Similar to the table, the flow is path search → text search within each element.

List<WebElement> listElements = driver.findElements(By.xpath("//ul[@class='nav navbar-nav navbar-right']/li/a"));
WebElement targetElement = null;
for(WebElement element : listElements ) {
    if (element.getText().indexof("PRODUCT002") > 1) {
        targetElement = element;
    }
}
targetElement.click();

10) Search by label

Examples that can be searched by label:

image.png

An example of searching for label in combination with the for attribute is as follows.

driver.findElement(By.xpath("//label[@for='mng_group_mail']")).click();

A pattern with a long label that partially matches. The syntax is the same as 4) -6).

driver.findElement(By.xpath("//label[contains(@for,'Part of the description')]")).click();

11) Search by linkText

From here, it will be a pattern to search by the displayed text.

It's a last resort (?) To move on when there are no searchable attributes and the tag structure is automatically generated, but I feel like I don't know what I'm testing.

linkText Search example:

image.png

If you want to search the text by exact match, it will be as follows.

driver.findElement(By.linkText("Save")).click();

Examples of text with line breaks and comments;

image.png

Make a partial match with partialLinkText.

driver.findElement(By.partialLinkText("VA User1")).click();

12) Search by text

Text search example:

image.png

If you can not get it even with linkText (such as when the operation at the time of pressing is described in javascript), get it with text and press it.

driver.findElement(By.xpath("//*[text()=\"PRINT\"]")).click();

Others (supplement, etc.)

--In the example, the click method is used, but in IE, you may not be able to proceed unless you use the sendkeys method. Actually, I think that the processing will be divided for each browser like the following.

if (browser.equals(_BROWSER_IE) || browser.equals(_BROWSER_EDGE)) {
    driver.findElement(By.xpath("//input[@value='OK']")).sendKeys(Keys.ENTER);
} else {
    driver.findElement(By.xpath("//input[@value='OK']")).click();
}

Recommended Posts

Summary of how to select elements in Selenium
Summary of how to implement default arguments in Java
[java] Summary of how to handle char
Summary of how to write annotation arguments
[Java] [Maven3] Summary of how to use Maven3
[Webpacker] Summary of how to install Bootstrap and jQuery in Rails 6.0
[java] Summary of how to handle character strings
Summary of how to create JSF self-made tags
[Swift] Summary of how to remove elements from an array (personal note)
[Java] Summary of how to abbreviate lambda expressions
[Rails] How to use select boxes in Ransack
How to use JQuery in js.erb of Rails6
How to insert processing with any number of elements in iterative processing in Ruby
[Swift] How to get the number of elements in an array (super basic)
How to hover and click on Selenium DOM elements
How to use CommandLineRunner in Spring Batch of Spring Boot
Summary of Java communication API (1) How to use Socket
How to test file upload screen in Spring + Selenium
Summary of Java communication API (3) How to use SocketChannel
Summary of Java communication API (2) How to use HttpUrlConnection
Summary of how to use the proxy set in IE when connecting with Java
How to display the select field of time_select every 30 minutes
How to select a specified date by code in FSCalendar
How to add elements without specifying the length of the array
How to implement one-line display of TextView in Android development
How to derive the last day of the month in Java
How to disable existing selected items in the select box
How to make th: value of select have multiple values
How to change BackgroundColor etc. of NavigationBar in Swift UI
How to install JavaScript library "select2" that makes multiple selections of selectbox fashionable in Rails 6.0
How to use Lombok in Spring
How to find May'n in XPath
How to hide scrollbars in WebView
How to run JUnit in Eclipse
How to iterate infinitely in Ruby
[Rails] How to write in Japanese
How to run Ant in Gradle
How to master programming in 3 months
How to learn JAVA in 7 days
How to get parameters in Spark
How to use setDefaultCloseOperation () of JFrame
How to install Bootstrap in Ruby
How to use InjectorHolder in OpenAM
How to introduce jQuery in Rails 6
How to use classes in Java?
How to name variables in Java
How to set Lombok in Eclipse
How to write easy-to-understand code [Summary 3]
How to concatenate strings in java
How to install Swiper in Rails
[Sprint Boot] How to use 3 types of SqlParameterSource defined in org.springframework.jdbc.core.namedparam
Summary of problems that I could not log in to firebase
How to write ruby if in one line Summary by beginner
How to delete large amounts of data in Rails and concerns
How to get the id of PRIMAY KEY auto_incremented in MyBatis
[Ruby on Rails] "|| =" ← Summary of how to use this assignment operator
How to output a list of strings in JSF as comma-separated strings
How to implement UI automated test using image comparison in Selenium
I want to change the value of Attribute in Selenium of Ruby
How to get the length of an audio file in java
How to increment the value of Map in one line in Java