javaseleniumtestinghighchartskatalon-recorder

Selenium: How to relate an id or a class to a specific div?


I tried to search before asking but I didn't find (or understand) the right answer for my issue.

I'm testing some charts (powered by Highcharts 6). I have 6 different charts on the same url. Each one is in a div container which has the different elements inside it (buttons, etc.).

The class and/or ID for all the buttons are the same.
For example, this is the Maximize/Minimize button for chart1:

<a class="has-tooltip btn btn-default change" role="button" title="" id="table" data-original-title="TEXT">
<span class="fa fa-lg ik-wi-icon-th"></span></a>

And here is the same button for chart2:

<a class="has-tooltip btn btn-default change" role="button" title="" id="table" data-original-title="TEXT">
<span class="fa fa-lg ik-wi-icon-th"></span></a>

They are exactly the same. So I tried to use Katalon Recorder to figure out how it can notice that I am clicking different buttons and this is what I get:

driver.findElement(By.xpath("//a[@id='table']/span")).click(); click1
driver.findElement(By.xpath("//a[@id='table']/span")).click(); click2

driver.findElement(By.xpath("(//a[@id='table']/span)[2]")).click(); click1
driver.findElement(By.xpath("(//a[@id='table']/span)[2]")).click(); click2

Where did this [2] come from?
How can tell Selenium which button I want to click?


Solution

  • The 2 came from, DOM wise, the second //a[@id='table']/span in the HTML.

    Lets say you have 6 graphs, and they all have a link with id='table' and they all have a span under it, this means that //a[@id='table']/span is going to return 6 elements. With xpath, only when you are sure that the sequence of your graphs is not going to change, you can say that to click the first graph:

    driver.findElement(By.xpath("//a[@id='table']/span")).click();
    

    Second:

    driver.findElement(By.xpath("(//a[@id='table']/span)[2]")).click();
    

    Third:

    driver.findElement(By.xpath("(//a[@id='table']/span)[3]")).click();
    

    etc.

    To be absolutely sure, hit F12 in chrome while on the page you want to test. Then go to Console, and typ:

    $x("//a[@id='table']/span")
    

    It will probably return 6 elements. When you open each of these elements and mouse-over them, Chrome will highlight the element it has found. Now if you want the fifth element Chrome found, typ this in console:

    $x("(//a[@id='table']/span)[5]")
    

    And now see if the element returned is the fifth on the page.