Getting xpath of an element based on the tag

Hi
I want to get the xpath of all the elements that have a tag.
I will get the count of the elements that have a tag a using findelementsBytagName a.
Then in the for loop I want to get the xpath of each element that has tag a and then click it using the xpath.
Please share the solution for this.

Regards
Kavya

Hi @kavyavijaya

Perhaps you can achieve it by using Selenium WebDriver inside Katalon.

import org.openqa.selenium.By
import org.openqa.selenium.WebDriver
import org.openqa.selenium.chrome.ChromeDriver
 
System.setProperty("webdriver.chrome.driver", DriverFactory.getChromeDriverPath())
WebDriver driver = new ChromeDriver()
// Here you navigate to your website
driver.navigate().to("YourWebsite");
// Here you retrieve the list of elements by an XPath ( in your case this should be "//a" )
List listOfElements = driver.findElements(By.xpath("//a"))
// Loop through all these elements and click them
for(WebElement element : listOfElements){
     element.click();
}

Note I haven’t tested the code yet, it’s just to give you a rough idea of how to accomplish it.

If you want to convert these elements into TestObject ( not really a TestObject as in they will exist in the Object Repository, but as temporary TestObjects to continue working with Katalon’s native methods in your script ), then you can use the solution the following post.

Hi
Thanks for the reply. I want to do this by tag name as the xpath contains the tag a . I will try and let you know.

Regards
kavya

A simpler way to get the driver:

List<WebElement> elements = DriverFactory.getWebDriver().findElements(By.xpath(“//a”));
for(WebElement element : elements) {
    element.click();
}

This will also work with whichever driver you currently have open, not just chrome.

1 Like