Working with
links in selenium
If
your requirement is to identify and perform action on link it is suggested to
use
1. By.LinkText()
2. By.partialLinkText()
methods.
How a link designed by the HTML developers?
The tags used to produce links are the <a> and </a>.
The content inside
the <a> and </a> is the linktext as shown below
If you are able to
see anchor tag for the control then you can use any of the above two methods If
not you cannot use LinkText() or PartialLinkText() methods.
LinkText():
If you want to use complete link text then you can use
linktext method
Code:
WebElement
ele=driver.findElement(By.linkText("Gmail"));
ele.click();
Partial
LinkText():
If your linktext is changing
dynamically i.e changing every time when you load a webpage then you have to
use this method. You can identify the element with part of the linktext which
is stable(Not changing) using partialLinkText() method.
Code:
WebElement
ele=driver.findElement(By.partialLinkText("Gma"));
ele.click();
Programme to find all
the links on the webpage:
import
java.util.List;
import
org.openqa.selenium.By;
import
org.openqa.selenium.WebDriver;
import
org.openqa.selenium.WebElement;
import
org.openqa.selenium.chrome.ChromeDriver;
public class
FindingAllLinks {
public static void
main(String[] args) {
System.setProperty("webdriver.chrome.driver", "");
WebDriver driver = new
ChromeDriver();
driver.get("http://google.com");
// Links
always starts with anchor tag so you can use
Findlements methods to get all the links on the webpage
List<WebElement>
allLinks=driver.findElements(By.tagName("a"));
// Use foreach
loop to iterate through all the links
for (WebElement
link : allLinks)
{
System.out.println(link.getText());
}
}
}
0 comments:
Post a Comment