-1

This is my HTML tree:

<div data-focusable="true" tabindex="0" class="css-1dbjc4n" data-testid="nav-Look up items-item"><div class="css-1dbjc4n"><div class="css-1dbjc4n" data-testid="nav-Look up items-item-Look up items-icon"><div class="css-1dbjc4n"><div dir="auto" class="css-901oao r-1awozwy" data-testid="nav-Look up items-item-Look up items">Look up items</div>

I am trying to locate the element by data-testid

I have used css selector and xpath which looks like the following:

@FindBy(css = "div[data-testid='nav-Look up items-item']")
@FindBy(xpath = "//div[@data-testid='nav-Look up items-item']")

But it is not able to locate the element.

Can anyone please help? Thank you.

Talima
  • 1
  • 1
  • 3

2 Answers2

0

I'm just going to re-write your tree here because this is easier for me to understand this way.

<div data-focusable="true" tabindex="0" class="css-1dbjc4n" data-testid="nav-Look up items-item">
    <div class="css-1dbjc4n">
        <div class="css-1dbjc4n" data-testid="nav-Look up items-item-Look up items-icon">
            <div class="css-1dbjc4n">
                <div dir="auto" class="css-901oao r-1awozwy" data-testid="nav-Look up items-item-Look up items">Look up items</div>
            </div>
        </div>
    </div>
</div>

You could always try selecting the className with something like this:

WebElement element = driver.findElement(By.className("css-901oao"));

or

WebElement element = driver.findElement(By.className("r-1awozwy"));

If that doesn't work you could try using a Chrome Extension like xPath Finder to try to find the absolute xPath and find it using something like:

WebElement element = driver.findElement(By.xpath("/html/body/div/div/div/div/div"));

But as your trying to select a div the className is more likely to work

Royginald
  • 125
  • 1
  • 10
  • Thanks for the answer but since data test id is the only valid concrete name in this tree, I can use only that. Any idea how to use data test id? – Talima Aug 17 '21 at 01:11
  • does [this](https://stackoverflow.com/questions/26304224/find-element-by-attribute) help? you could try something like `driver.findElement(By.cssSelector("div[data-testid='nav-Look up items-item-Look up items']"));` – Royginald Aug 17 '21 at 01:51
  • this is what I tried at first, didnt work :( @Royginald – Talima Aug 17 '21 at 02:16
  • That's strange, it seems to work for me. Can you add the code where you store the element in a variable and the first action you perform? – Royginald Aug 17 '21 at 22:36
0

You should use it like this

@FindBy(xpath = "//div[@data-testid='nav-Look up items-item']")
WebElement lookUpItems;

and you can (let's say wanna perform .click)

lookUpItems.click();
cruisepandey
  • 28,520
  • 6
  • 20
  • 38