This post was most recently updated on June 14th, 2019
Locator Type: Link Text or Partial Link Text.
- This locator is used to locate anchor web element using it’s text.
- Link text is a element text between opening <a> and closing anchor tag </a>.
- Partial link text is used to find anchor element similar to point 1 but it used partial unique text to locate element. It is useful to get rid of large link text.
Java code to find web element
Using link text
→ WebElement linkTextElement=driver.findElement(By.linkText("Link_text"));
Using partial link text
→ WebElement plinkTextElement=driver.findElement(By.partialLinkText("Partial_Link_Text"));
Example →
To locate element using link text:
-
- Go to https://www.societyhive.com/
- Inspect menu option FEATURE
- Use link text to find web element.
WebElement linkText=driver.findElement(By.linkText("FEATURES"));
To locate element using partial link text:
-
- Go to https://www.societyhive.com/
- Inspect for link contains text “cooperative housing societies”
- Use partial link text to find web element.
WebElement partialLinkText=driver.findElement(By.partialLinkText("cooperative housing societies"));
Perform click on Link(find by link text and partial link text):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; public class SeleniumMain { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "./chromedriver.exe"); WebDriver driver; ChromeOptions cOptions=new ChromeOptions(); cOptions.addArguments("--start-maximized"); driver=new ChromeDriver(cOptions); driver.get("https://www.societyhive.com/"); WebElement linkToFeatures=driver.findElement(By.linkText("FEATURES")); linkToFeatures.click(); WebElement partialLinkToHousingSocieties=driver.findElement(By.partialLinkText("cooperative housing societies")); partialLinkToHousingSocieties.click(); driver.close(); } } |