- Selenium Testing Tools Cookbook(Second Edition)
- Unmesh Gundecha
- 303字
- 2021-07-09 21:14:19
Finding links
Selenium WebDriver provides two special methods to find links on a page. Links can be searched either by their text or by partial text.
Finding links with partial text comes in handy when links have dynamic text. In this recipe, we will see how to use these methods to find links.
How to do it...
Let's create a simple test to see how finding links works in Selenium WebDriver with the following options.
Selenium WebDriver's By
class provides the linkText()
method to locate links using text displayed for the link. In the following example, we will locate the Gmail link displayed on the Google Home page:
WebElement gmailLink = driver.findElement(By.linkText("GMail")); assertEquals("http://mail.google.com/", gmailLink.getAttribute("href"));
Selenium WebDriver's By
class also provides a method to locate links using partial text. This method is useful where developers create links with dynamic text. In this example, a link is provided to open the inbox. This link also displays the number of new e-mails, which may change dynamically. Here, we can use the partialLinkText()
method to locate the link using a fixed or known portion of the link text, which in this case would be Index
. The following code shows an example:
WebElement inboxLink = driver.findElement(By.partialLinkText("Inbox")); System.out.println(inboxLink.getText());
How it works...
The linkText
and partialLinkText
locator methods query the driver for all the links that meet the specified text and return the matching link(s).
There's more...
You can also locate links using the id
, name
, or class
attributes, if developers have provided these attributes.
See also
- The Finding an element using the findElement method recipe
- The Finding elements using findElements method recipe
- Python進(jìn)階編程:編寫更高效、優(yōu)雅的Python代碼
- Python Network Programming Cookbook(Second Edition)
- Python時(shí)間序列預(yù)測(cè)
- 計(jì)算機(jī)應(yīng)用基礎(chǔ)實(shí)踐教程
- Getting Started with Hazelcast(Second Edition)
- ASP.NET程序開發(fā)范例寶典
- JavaScript腳本特效編程給力起飛
- 從零開始學(xué)算法:基于Python
- Building Clouds with Windows Azure Pack
- 算法訓(xùn)練營(yíng):海量圖解+競(jìng)賽刷題(入門篇)
- HTML5+CSS+JavaScript深入學(xué)習(xí)實(shí)錄
- Switching to Angular 2
- Web 2.0策略指南
- R Data Visualization Cookbook
- Odoo Development Essentials