官术网_书友最值得收藏!

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.

Finding a link by its text

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"));

Finding a link by partial text

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.

Note

Locating elements based on text can cause issues while testing applications in multiple locales. Using parameterized text locator values could work in such scenarios.

See also

  • The Finding an element using the findElement method recipe
  • The Finding elements using findElements method recipe
主站蜘蛛池模板: 白沙| 铅山县| 繁峙县| 松原市| 保定市| 克东县| 井陉县| 基隆市| 普陀区| 芜湖市| 南宁市| 察哈| 恩施市| 铁力市| 米脂县| 长治县| 运城市| 东辽县| 通海县| 绥江县| 平南县| 长乐市| 大姚县| 安福县| 博野县| 桐庐县| 三门县| 沁源县| 城固县| 浏阳市| 裕民县| 兴山县| 凤冈县| 清涧县| 桂林市| 满洲里市| 定远县| 习水县| 望都县| 霞浦县| 盐边县|