How To Locate Element By Link Text And Partial Link Text Locators
In the previous post we have seen “locators in Selenium“. In this post, we discuss “How To Locate Element By Link Text And Partial Link Text Locators”. Find the below links on How to find elements on a web page using different types of locators.
1. “How To Locate Element By ID Locator”
2. “How To Locate Element By Name Locator”
3. “How To Locate Element By Class Name Locator”
4. “How To Locate Element By Tag Name Locator”
5. “How To Locate Element By CSS Selector Locator”
6. “How To Locate Element By XPath Locator”
Coming to the actual post “How To Locate Element By Link Text and Partial Link Text Locators”.
Link Text Locator:
If there are multiple elements with the same link text then the first one will be selected. This Link Text locator works only on links (hyperlinks) so it is called as Link Text locator.
Syntax:
findElement(By.linkText("LinkText"))
<span id="link-signup">
<a href="https://accounts.google.com/SignUp?service=mail&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F"> Create account </a>
</span>
Value to be added in the By.linkText method:
findElement(By.linkText("Create account"))
Script:
package seleniumTutorial; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class Locators { public static void main (String [] args){ WebDriver driver = new FirefoxDriver(); driver.get("<a href="https://www.gmail.com/" target="_blank" data-saferedirecturl="https://www.google.com/url?hl=en&q=https://www.gmail.com&source=gmail&ust=1475225889620000&usg=AFQjCNGWiJEPM95P3VkSISyTSrTuSE2t5A">https://www.gmail.<wbr />com</a>"); driver.findElement(By.linkText("Create account")).click(); } }
Partial Link Text:
In some situations, we may need to find links by a portion of the text in a Link Text element. it contains. In such situations, we use Partial Link Text to locate elements.
Syntax:
findElement(By.partialLinkText("partialLinkText"))
<span id="link-signup">
<a href="https://accounts.google.com/SignUp?service=mail&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F"> Create account </a>
</span>
Value to be added in the By.partialLinkText method:
findElement(By.partialLinkText("Create"))
Script:
package seleniumTutorial; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class Locators { public static void main (String [] args){ WebDriver driver = new FirefoxDriver(); driver.get("https://www.gmail.com"); driver.findElement(By.partialLinkText("Create")).click(); } }