0

I have the following HTML code where I need to detect the number of records displayed on the page and select the correct record. However, inspecting the elements with Firefox show the records are having the same class name while the id of the WebElement is dynamically created.

If I use it to locate by tag name, it will return more than 100 Web elements.

May I know how do I identify use XPath or CSS selector to obtain the first record displayed on the page.

enter image description here

    WebElement menuList = driver.findElement(By.cssSelector(".scrollable-content"));
    List<WebElement> search_li = menuList.findElements(By.tagName("div"));
    WebElement searchresult = driver.findElement(By.ByXPath.className("grid-view-drop-area ng-star-inserted"));
    searchresult.click();
EeTze
  • 1
  • 1

2 Answers2

0

Thank you DebanjanB and Guy for your valueable input.

I used the combination of your input to get identify the unique UI object.

List<WebElement> searchresult = driver.findElements(By.xpath("//div[@class='scrollable-content']/div[@class='grid-view-drop-area ng-star-inserted' and starts-with(@id, 'grid-row')]"));
searchresult.get(0).click();
EeTze
  • 1
  • 1
  • Don't do that. Don't let Selenium decide what is `searchresult.get(0)` and `searchresult.get(1)`. Instead, lookout for the exact element you need. – undetected Selenium Feb 28 '20 at 06:30
-1

A bit of more information interms of the HTML of the expanded <div> tags would have helped us to construct a canonical answer. However, to extract the number of records displayed on the page you have to induce WebDriverWait for the visibilityOfAllElementsLocatedBy() and you can use either of the following Locator Strategies:

  • cssSelector:

    System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("div.grid-view-drop-area.ng-star-inserted[id^='grid-row']"))).size());
    
  • xpath:

    System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//div[@class='grid-view-drop-area ng-star-inserted' and starts-with(@id, 'grid-row')]"))).size());
    

To obtain the first record you can use either of the following solution:

  • cssSelector:

    WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibility_of_element_located(By.cssSelector("div.scrollable-content>div.grid-view-drop-area.ng-star-inserted[id^='grid-row']")));
    
  • xpath:

    WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibility_of_element_located(By.xpath("//div[@class='scrollable-content']/div[@class='grid-view-drop-area ng-star-inserted' and starts-with(@id, 'grid-row')]")));
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352