Searching for Elements Through Known Elements

The aim is to generate CSS selectors and use them in automation code, in order to simplify the interaction with elements that are difficult to reach. Consider the following, slightly modified version of the DOM that we used in Retrieve Information from a Table:

<html>
<head>
<title>About Me</title>
</head>
<body>
<h1 id="about">About Me</h1>
<ul id="list" class="list-group">
<li class="list-group-item">Name: John Doe</li>
<li class="list-group-item">Phone: 400-6790</span></li>
<li class="list-group-item">Hometown: Springfield</span></
li>
</ul>
</body>
</html>

Note that the list elements no longer have unique IDs. We'll create CSS selectors to find the list elements, and we will use them to implement locators in Java code. You can use either the parent-child relationship or the sibling relationship. The steps for completion are as follows:

  1. Open https://trainingbypackt.github.io/Beginning-Selenium/lesson_4/exercise_4_2.html in the Chrome browser.
  2. Open the Chrome DevTools to try out the selectors indicated in the next steps.
  3. To identify the first item in the list (John Doe), use the selector #list to get its parent:

 The following screenshot shows what your screen should look like:

  1. Retrieve the first child of #list with li:first-child.
  2. Combine the two selectors (#list and li:first-child) to obtain a solid locator for the element that we are looking for.
  3. Use li:last-child rather than li:first-child, to reach the last item in the list.
  1. Use the nth-child keyword, combined with index 2, to reach the second item in the list. Since we need the second element, it will look as follows: li:nth-child(2). The complete selector will look as follows: #list li:nth-child(2).
  2. After all of the selectors have been found, use them to create the locators with Java:
WebElement user = driver.findElement(By.
cssSelector("form#login > input:first-child + input"));
WebElement user = driver.findElement(By.
cssSelector("form#login > input:nth-child(2) + input"));
Sometimes, the creation of an effective element locator is not straightforward, because the element doesn't have an ID or any distinctive attributes.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.2.15