I'm new to Selenium webdriver. I came across a requirement where I have to run my test which clicks on all links with in a section. Can someone help me with the Java code for this. Attached a image which shows firebug properties of that particular section. I have tried the below code but it returns me a null list.
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("https://dev.www.tycois.com/");
driver.manage().window().maximize();
List<WebElement> allElements = driver.findElements(By.xpath("html/body/div[10]/div/div[1]/div[3]/ul[1]/li[5]"));
System.out.println(allElements);
for (WebElement element: allElements) {
System.out.println(element.getText());
element.click();
}
}
Thanks in advance.
The details aren't clear but it looks like you are trying to print the links in the INDUSTRIES section of the footer. If that's true, this should work.
driver.get("https://dev.www.tycois.com/");
WebElement industries = driver.findElement(By.cssSelector("div.columns.three.alpha > ul"));
List<WebElement> links = industries.findElements(By.tagName("li"));
for (int i = 1; i < links.size(); i++)
{
System.out.println(links.get(i).getText());
}
You can't click the links in this loop because once you click the first one, you will no longer be on the page. I would suggest that you store the URLs from each link in an array and then driver.get(url)
for each one. Or you could store the expected URLs in an array and compare the URLs from the links to the expected URLs and not have to navigate at all. The choice is up to you...
The solution from JeffC works with the tweak detailed below -
driver.get("https://dev.www.tycois.com/");
WebElement industries =
driver.findElement(By.cssSelector("div.columns.three.alpha > ul"));
List<WebElement> links = industries.findElements(By.tagName("li"));
for (int i = 0; i < links.size(); i++)
{
System.out.println(links.get(i).getText());
}
The alternate answer above, which I cannot comment on because I'm new to the site had
for(int i=1; i < links.size(); i++)
However this misses off the first element in the list. The suggested fix to use -
for(int i=1; i <= links.size(); i++)
will cause an IndexOutOfBoundsException.
To fix, simply set your iterator to start at 0 instead of 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With