accessing-links-tables-selenium-webdriver

来源:互联网 发布:java传值还是传引用 编辑:程序博客网 时间:2024/06/05 13:24

In this tutorial, we are going to learn about accessing links & Tables using Webdriver

 

Accessing Links

Links Matching a Criterion

Links can be accessed using an exact or partial match of their link text. The examples below provide scenarios where multiple matches would exist, and would explain how WebDriver would deal with them.

Exact Match

Accessing links using their exact link text is done through the By.linkText() method. However, if there are two links that have the very same link text, this method will only access the first one. Consider the HTML code below

 

When you try to run the WebDriver code below, you will be accessing the first “click here” link

.

 

As a result, you will automatically be taken to Google.

 

Partial Match

Accessing links using a portion of their link text is done using the By.partialLinkText() method. If you specify a partial link text that has multiple matches, only the first match will be accessed. Consider the HTML code below.

When you execute the WebDriver code below, you will still be taken to Google.

Case-sensitivity

The parameters for By.linkText() and By.partialLinkText() are both case-sensitive, meaning that capitalization matters. For example, in Mercury Tours’ homepage, there are two links that contain the text “egis” – one is the “REGISTER” link found at the top menu, and the other is the “Register here” link found at the lower right portion of the page.

Though both links contain the character sequence “egis”, the "By.partialLinkText()" method will access these two links separately depending on capitilization of the characters. See the sample code below.

All Links

One of the common procedures in web testing is to test if all the links present within the page are working. This can be conveniently done using a combination of the Java for-each loop and the By.tagName(“a”) method. The WebDriver code below checks each link from the Mercury Tours homepage to determine those that are working and those that are still under construction.

 

01.package practice_webdriver;
02. 
03.import java.util.List;
04. 
05. 
06. 
07.import java.util.concurrent.TimeUnit;
08. 
09.import org.openqa.selenium.*;
10. 
11.import org.openqa.selenium.firefox.FirefoxDriver;
12. 
13.import org.openqa.selenium.support.ui.ExpectedConditions;
14. 
15.import org.openqa.selenium.support.ui.WebDriverWait;
16. 
17. 
18. 
19.public class AllLinks {
20. 
21. 
22. 
23.public static void main(String[] args) {
24. 
25.String baseUrl = "http://newtours.demoaut.com/";
26. 
27.WebDriver driver = new FirefoxDriver();
28. 
29.String underConsTitle = "Under Construction: Mercury Tours";
30. 
31.driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
32. 
33. 
34. 
35.driver.get(baseUrl);
36. 
37.List<WebElement> linkElements = driver.findElements(By.tagName("a"));
38. 
39.String[] linkTexts = new String[linkElements.size()];
40. 
41.int i = 0;
42. 
43. 
44. 
45.//extract the link texts of each link element
46. 
47.for (WebElement e : linkElements) {
48. 
49.linkTexts[i] = e.getText();
50. 
51.i++;
52. 
53.}
54. 
55. 
56. 
57.//test each link
58. 
59.for (String t : linkTexts) {
60. 
61.driver.findElement(By.linkText(t)).click();
62. 
63.if (driver.getTitle().equals(underConsTitle)) {
64. 
65.System.out.println("\"" + t + "\""
66. 
67." is under construction.");
68. 
69.else {
70. 
71.System.out.println("\"" + t + "\""
72. 
73." is working.");
74. 
75.}
76. 
77.driver.navigate().back();
78. 
79.}
80. 
81.driver.quit();
82. 
83.}
84. 
85.}

The output should be similar to the one indicated below.

Links Outside and Inside a Block

The latest HTML5 standard allows the <a> tags to be placed inside and outside of block-level tags like <div>, <p>, or <h1>. The "By.linkText()" and "By.partialLinkText()" methods can access a link located outside and inside these block-level elements. Consider the HTML code below.

The WebDriver code below accesses both of these links using By.partialLinkText() method.

The output above confirms that both links were accessed successfully because their respective page titles were retrieved correctly.

Accessing Image Links

Image links are images that act as references to other sites or sections within the same page. Since they are images, we cannot use the By.linkText() and By.partialLinkText() methods because image links basically have no link texts at all. In this case, we should resort to using either By.cssSelector or By.xpath. The first method is more preferred because of its simplicity.

In the example below, we will access the “Facebook” logo on the upper left portion of Facebook’s Password Recovery page.

 

We will use By.cssSelector and the element’s “title” attribute to access the image link. And then we will verify if we are taken to Facebook’s homepage.

 

01.package practice_webdriver;
02. 
03. 
04. 
05.import org.openqa.selenium.*;
06. 
07.import org.openqa.selenium.firefox.FirefoxDriver;
08. 
09. 
10. 
11.public class ImageLink {
12. 
13. 
14. 
15.public static void main(String[] args) {
16. 
17.String baseUrl = "https://www.facebook.com/login/identify?ctx=recover";
18. 
19.WebDriver driver = new FirefoxDriver();
20. 
21. 
22. 
23.driver.get(baseUrl);
24. 
25.//click on the "Facebook" logo on the upper left portion
26. 
27.driver.findElement(By.cssSelector("a[title=\"Go to Facebook Home\"]")).click();
28. 
29. 
30. 
31.//verify that we are now back on Facebook's homepage
32. 
33.if (driver.getTitle().equals("Welcome to Facebook - Log In, Sign Up or Learn More")) {
34. 
35.System.out.println("We are back at Facebook's homepage");
36. 
37.else {
38. 
39.System.out.println("We are NOT in Facebook's homepage");
40. 
41.}
42. 
43.driver.quit();
44. 
45.}
46. 
47.}
 
Result

 

Reading a Table

There are times when we need to access elements (usually texts) that are within HTML tables. However, it is very seldom for a web designer to provide an id or name attribute to a certain cell in the table. Therefore, we cannot use the usual methods such as “By.id()”, “By.name()”, or “By.cssSelector()”. In this case, the most reliable option is to access them using the “By.xpath()” method.

XPath Syntax

Consider the HTML code below.

We will use XPath to get the inner text of the cell containing the text “fourth cell”. 

Step 1 – Set the Parent Element (table)

XPath locators in WebDriver always start with a double forward slash “//” and then followed by the parent element. Since we are dealing with tables, the parent element should always be the <table> tag. The first portion of our XPath locator should therefore start with “//table”.

Step 2 – Add the child elements

The element immediately under <table> is <tbody> so we can say that <tbody> is the “child” of <table>. And also, <table> is the “parent” of <tbody>. All child elements in XPath are placed to the right of their parent element, separated with one forward slash “/” like the code shown below.

                                  

Step 3 – Add Predicates

The <tbody> element contains two <tr> tags. We can now say that these two <tr> tags are “children” of <tbody>. Consequently, we can say that <tbody> is the parent of both the <tr> elements.

Another thing we can conclude is that the two <tr> elements are siblings. Siblings refer to child elements having the same parent.

To get to the <td> we wish to access (the one with the text “fourth cell”), we must first access the second <tr> and not the first. If we simply write “//table/tbody/tr”, then we will be accessing the first <tr> tag.

So, how do we access the second <tr> then? The answer to this is to use Predicates.

Predicates are numbers or HTML attributes enclosed in a pair of square brackets “[ ]” that distinguish a child element from its siblings. Since the <tr> we need to access is the second one, we shall use “[2]” as the predicate.

If we won’t use any predicate, XPath will access the first sibling. Therefore, we can access the first <tr> using either of these XPath codes.

Step 4 – Add the Succeeding Child Elements Using the Appropriate Predicates

The next element we need to access is the second <td>. Applying the principles we have learned from steps 2 and 3, we will finalize our XPath code to be like the one shown below.

Now that we have the correct XPath locator, we can already access the cell that we wanted to and obtain its inner text using the code below. It assumes that you have saved the HTML code above as “newhtml.html” within your C Drive.

 

Accessing Nested Tables

The same principles discussed above applies to nested tables. Nested tables are tables located within another table. An example is shown below.

To access the cell with the text “4-5-6” using the “//parent/child” and predicate concepts from the previous section, we should be able to come up with the XPath code below.

 

The WebDriver code below should be able to retrieve the inner text of the cell which we are accessing.

The output below confirms that the inner table was successfully accessed.

Using Attributes as Predicates

If the element is written deep within the HTML code such that the number to use for the predicate is very difficult to determine, we can use that element’s unique attribute instead.

In the example below, the “New York to Chicago” cell is located deep into Mercury Tours homepage’s HTML code.

 

In this case, we can use the table’s unique attribute (width=”270”) as the predicate. Attributes are used as predicates by prefixing them with the @ symbol. In the example above, the “New York to Chicago” cell is located in the first <td> of the fourth <tr>, and so our XPath should be as shown below.

Remember that when we put the XPath code in Java, we should use the escape character backward slash “\” for the double quotation marks on both sides of “270” so that the string argument of By.xpath() will not be terminated prematurely.

We are now ready to access that cell using the code below.

 

Shortcut: Use Firebug

If the number or attribute of an element is extremely difficult or impossible to obtain, the quickest way to generate the XPath code is thru Firebug.

Consider the example below from Mercury Tours homepage.

Step 1

Use Firebug to obtain the XPath code.

 

Step 2

Look for the first “table” parent element and delete everything to the left of it.

Step 3

Prefix the remaining portion of the code with double forward slash “//” and copy it over to your WebDriver code.

The WebDriver code below will be able to successfully retrieve the inner text of the element we are accessing.

Summary

  • Accessing links using their exact match is done using By.linkText() method.
  • Accessing links using their partial match is done using By.partialLinkText() method.
  • If there are multiple matches, By.linkText() and By.partialLinkText() will only select the first match.
  • Pattern matching using By.linkText() and By.partialLinkText() is case-sensitive.
  • The By.tagName("a") method is used to fetch all links within a page.
  • Links can be accessed by the By.linkText() and By.partialLinkText() whether they are inside or outside block-level elements.
  • Accessing image links are done using By.cssSelector() and By.xpath() methods.
  • By.xpath() is commonly used to access table elements.


原创粉丝点击