How to search XPath in Selenium

selenium-learningBOX

Nice to meet you. My name is Matoba from the Development Department.
I joined the company in May this year and am in charge of E2E test automation.
In this article, I will show you how to use Seleniumn's XPath to specify the elements in a page.

Click here for table of contents

What is XPath?

XPath is an XML format document toThis is a simple language for specifying and retrieving a specific part.
And even though it's for XML, you can use it for HTML as well.

How to write basic XPath

Let's take a look at how to write XPath.

(Example.)


 <!DOCTYPE html>
  <html>
  <head>
   <title龍野情報システム/title>
  </head>
  </html>

For HTML, such as the above

html - head - title

It can be represented by such a hierarchical structure.
When writing in XPath, html tags can be separated by / (slash) and represented by a hierarchical structure of tags, as shown below.

/html/head/title

If you want to omit a path, you can omit the previous element by using // as shown below.

//title

How to get XPath using attributes

Attributes that are associated with or linked to elements, such as class and id, are represented by "@".

(Example.)


 <div class="wrapper">

 <div id="logo">


//*[@class="wrapper"].

//*[@id="logo"]]

Thus, if you want to display a specific attribute value, use @ (atmark).
Also, * (asterisk) means all elements.
If you specify a specific element from the same class or id

(Example.)



.


As shown above, if you want to retrieve only the employment information, you can search for the string contained in the text.
Also.contains(text(),search string)I'll show you how you can easily specify a string using

For example, if you write the following, it will specify the following four items: Philosophy and Vision, History, Employment Information, and Contact Us.
//*[@id="menu-item"]

In such a case, you can write like this to specify only the inquiry part.
//*[@id="menu-item"]//*[contains(text(), "Contact"]]

Get XPath in Google Chrome

If you can't specify the XPath well, you can use Chrome's validation feature to get it.
Use the "verification feature" listed in Chrome and right-click on the blue highlighted area.

[Copy Menu] → [Copy XPath].
You can copy it to the clipboard by doing

summary

In this article, we introduced the XPath search method in Selenium.
The following is just one example, but we hope it will be helpful.
I'll summarize a more detailed specification method in the next article.

en_USEnglish