[Selenium+Java] Implicit Wait & Explicit Wait in Selenium

https://www.guru99.com/handling-dynamic-selenium-webdriver.html

here are two types of HTML tables published on the web-

  1. Static tables: Data is static i.e. Number of rows and columns are fixed.
  2. Dynamic tables: Data is dynamic i.e. Number of rows and columns are NOT fixed.

Below is an example of a dynamic table of Sales. Based on input date filters, number of rows will get altered. So, it is dynamic in nature.

Handling static table is easy, but dynamic table is a little bit difficult as rows and columns are not constant.

In this tutorial, you will learn-

Using X-Path to Locate Web Table Elements

Before we locate web element, first let‘s understands-

What is a web element?

Web elements are nothing but HTML elements like textbox, dropdowns radio buttons, submit buttons, etc. These HTML elements are written with start tag and ends with an end tag.

For Example,

<p> My First HTML Document</p>.

Steps for getting X-path of web element that we want to locate.

Step 1) In Chrome, Go to http://money.rediff.com/gainers/bsc/daily/groupa

Step 2) Right click on web element whose x-path is to be fetched. In our case, right click on "Company" Select Inspect option. The following screen will be shown -

Step 3) Right Click on highlighted web element > Select Copy -> Copy x-path option.

Step 4) Use the copied X-path "//*[@id="leftcontainer"]/table/thead/tr/th [1]" in Selenium WebDriver to locate the element.

Example: Fetch number of rows and columns from Dynamic WebTable

When the table is dynamic in nature, we cannot predict its number of rows and columns.

Using Selenium web driver, we can find

  • Number of Rows and columns of web table
  • X row or Y column‘s data.

Below is program for fetching total number of rows and columns of web table.

import java.text.ParseException;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class Noofrowsandcols {
    public static void main(String[] args) throws ParseException {
    	WebDriver wd;
	  System.setProperty("webdriver.chrome.driver","G://chromedriver.exe");
	  wd= new ChromeDriver();
        wd.get("http://money.rediff.com/gainers/bsc/dailygroupa?");
        //No.of Columns
        List  col = wd.findElements(By.xpath(".//*[@id=\"leftcontainer\"]/table/thead/tr/th"));
        System.out.println("No of cols are : " +col.size());
        //No.of rows
        List  rows = wd.findElements(By.xpath(".//*[@id=‘leftcontainer‘]/table/tbody/tr/td[1]"));
        System.out.println("No of rows are : " + rows.size());
        wd.close();
    }
}

Code Explanation:

  • Here we have first declared Web Driver object "wd" &initialized it to chrome driver.
  • We use List <WebElement> to total number of columns in "col".
  • findElements commands returns a list of ALL the elements matching the specified locator
  • using findElements and X-path //*[@id=\"leftcontainer\"]/table/thead/tr/th we get all the columns
  • Similarly, we repeat the process for rows.

.

Output:

Example: Fetch cell value of a particular row and column of the Dynamic Table

Let‘s assume we need 3rd row of the table and its second cell‘s data. See the table below-

In above table, data is regularly updated after some span of time. The data you try retrieve will be different from the above screenshot. However, the code remains the same. Here is sample program to get the 3rd row and 2nd column‘s data.

import java.text.ParseException;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class RowandCell {
    public static void main(String[] args) throws ParseException {
    	WebDriver wd;
		System.setProperty("webdriver.chrome.driver","G://chromedriver.exe");
		 wd= new ChromeDriver();
		 wd.get("http://money.rediff.com/gainers/bsc/daily/groupa?");
		 wd.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
		 WebElement baseTable = wd.findElement(By.tagName("table"));

		 //To find third row of table
		 WebElement tableRow = baseTable.findElement(By.xpath("//*[@id=\"leftcontainer\"]/table/tbody/tr[3]"));
         String rowtext = tableRow.getText();
		 System.out.println("Third row of table : "+rowtext);

		    //to get 3rd row‘s 2nd column data
		    WebElement cellIneed = tableRow.findElement(By.xpath("//*[@id=\"leftcontainer\"]/table/tbody/tr[3]/td[2]"));
		    String valueIneed = cellIneed.getText();
		    System.out.println("Cell value is : " + valueIneed);
		    wd.close();
    }
}

Code Explanation:

  • Table is located using locator property "tagname".
  • UsingXPath"//*[@id=\"leftcontainer\"]/table/tbody/tr[3]" find the 3rd row and gets its text using getText () function
  • Using Xpath "//*[@id=\"leftcontainer\"]/table/tbody/tr[3]/td[2]" find the 2nd cell in 3rd row and gets its text using getText () function

Output:

Example: Get Maximum of all the Values in a Column of Dynamic Table

In this example, we will get the maximum of all values in a particular column.

Refer the following table -

Here is the code

import java.text.ParseException;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.text.NumberFormat;

public class MaxFromTable {
    public static void main(String[] args) throws ParseException {
    	WebDriver wd;
		System.setProperty("webdriver.chrome.driver","G://chromedriver.exe");
		 wd= new ChromeDriver();
		 wd.get("http://money.rediff.com/gainers/bsc/daily/groupa?");
		 String max;
	     double m=0,r=0;

	       //No. of Columns
	        List  col = wd.findElements(By.xpath(".//*[@id=‘leftcontainer‘]/table/thead/tr/th"));
	        System.out.println("Total No of columns are : " +col.size());
	        //No.of rows
	        List  rows = wd.findElements(By.xpath (".//*[@id=‘leftcontainer‘]/table/tbody/tr/td[1]"));
	        System.out.println("Total No of rows are : " + rows.size());
	        for (int i =1;i<rows.size();i++)
	        {
	            max= wd.findElement(By.xpath("html/body/div[1]/div[5]/table/tbody/tr[" + (i+1)+ "]/td[4]")).getText();
	            NumberFormat f =NumberFormat.getNumberInstance();
	            Number num = f.parse(max);
	            max = num.toString();
	            m = Double.parseDouble(max);
	            if(m>r)
	             {
	                r=m;
	             }
	        }
	        System.out.println("Maximum current price is : "+ r);
    }
}

Code Explanation:

  • Using chrome driver we locate the web table and get total number of row using XPath ".//*[@id=‘leftcontainer‘]/table/tbody/tr/td[1]"
  • Using for loop, we iterate through total number of rows and fetch values one by one. To get next row we use (i+1) in XPath
  • We compare old value with new value and maximum value is printed at the end of for loop

OutPut

Example: Get all the values of a Dynamic Table

Consider the following table http://demo.guru99.com/test/table.html

The number of columns for each row is different.

Here row number 1, 2 and 4 have 3 cells, and row number 3 has 2 cells, and row number 5 has 1 cell.

We need to get values of all the cells

Here is the code:

import java.text.ParseException;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.chrome.ChromeDriver;

public class NofRowsColmns {
    public static void main(String[] args) throws ParseException {
    	WebDriver wd;
    	System.setProperty("webdriver.chrome.driver","G://chromedriver.exe");
    	wd = new ChromeDriver();
    	wd.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
    	wd.get("http://demo.guru99.com/test/table.html");
    	//To locate table.
    	WebElement mytable = wd.findElement(By.xpath("/html/body/table/tbody"));
    	//To locate rows of table.
    	List < WebElement > rows_table = mytable.findElements(By.tagName("tr"));
    	//To calculate no of rows In table.
    	int rows_count = rows_table.size();
    	//Loop will execute till the last row of table.
    	for (int row = 0; row < rows_count; row++) {
    	    //To locate columns(cells) of that specific row.
    	    List < WebElement > Columns_row = rows_table.get(row).findElements(By.tagName("td"));
    	    //To calculate no of columns (cells). In that specific row.
    	    int columns_count = Columns_row.size();
    	    System.out.println("Number of cells In Row " + row + " are " + columns_count);
    	    //Loop will execute till the last cell of that specific row.
    	    for (int column = 0; column < columns_count; column++) {
    	        // To retrieve text from that specific cell.
    	        String celtext = Columns_row.get(column).getText();
    	        System.out.println("Cell Value of row number " + row + " and column number " + column + " Is " + celtext);
    	    }
    	    System.out.println("-------------------------------------------------- ");
    	}
   	}
}

Code Explanation:

  • rows_count gives the total number of rows
  • for each row we get the total number of columns using rows_table.get(row).findElements(By.tagName("td"));
  • We iterate through each column and of each row and fetch values.

Output:

Summary

  • Static web tables are consistent in nature. i.e. they do have fixed number of rows as well as Cell data.
  • Dynamic web tables are inconsistent i.e. they do not have fixed number of rows and cells data.
  • Using selenium web driver, we can handle dynamic web tables easily.
  • Selenium Webdriver allows us to access dynamic web tables by their X-path

The article is contributed by Kanchan Kulkarni.

原文地址:https://www.cnblogs.com/alicegu2009/p/9076219.html

时间: 2024-10-17 00:27:39

[Selenium+Java] Implicit Wait & Explicit Wait in Selenium的相关文章

[Selenium+Java] Parallel Execution &amp; Session Handling in Selenium

Source URL: https://www.guru99.com/sessions-parallel-run-and-dependency-in-selenium.html To understand how to run scripts in parallel, let's first understand Why do we need Session Handling? During test execution, the Selenium WebDriver has to intera

[Selenium+Java] Listeners and their use in Selenium WebDriver

Original URL: https://www.guru99.com/listeners-selenium-webdriver.html TestNG Listeners in Selenium WebDriver There are two main listeners. WebDriver Listeners TestNG Listeners In this tutorial, we will discuss onTestngListeners. Here is what you wil

Selenium+Java 环境搭建

从事开发工作一年,测试工作三年,一直希望能够做自动化方面的测试,但因为各种缘由一直没做成,终于有时间自己学学.因为有一些java基础,所以从Selenium+Java开始. 搭建Selenium+Java环境过程发生很多问题,主要是浏览器版本和selenium jar包不兼容问题,在此做个总结. 先把所有需要的文件准备好: 1.jdk,可以直接官网下载,我这里是1.7  链接:http://pan.baidu.com/s/1dDDdAcp 密码:mt98 2.eclipse,可以直接官网下载  

[Selenium+Java] Handling AJAX Call in Selenium Webdriver

Original URL: https://www.guru99.com/handling-ajax-call-selenium-webdriver.html Handling AJAX Call in Selenium Webdriver Ajax is a technique used for creating fast and dynamic web pages. This technique is asynchronous and uses a combination of Javasc

Selenium+Java+Eclipse 自动化测试环境搭建

一.下载Java windows java下载链接 https://www.java.com/zh_CN/download/win10.jsp 二.安装Java 安装好后检查一下需不需要配置环境变量,现在java 8已经不用配置环境变量了,直接在命令行输入:java -version 三.下载和安装Eclipse windows Eclipse下载链接 https://www.eclipse.org/downloads/ 你也可以下载绿色版 四.下载selenium,然后解压 selenium

软件测试之Selenium Java WebDriver

编写Selenium Java WebDriver程序,测试inputgit.csv表格中的学号和git地址的对应关系 package selenium2; import java.util.regex.Pattern; import java.util.concurrent.TimeUnit; import org.junit.*; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import o

自动化测试框架selenium+java+TestNG——配置篇

最近来总结下自动化测试 selenium的一些常用框架测试搭配,由简入繁,最简单的就是selenium+java+TestNG了,因为我用的是java,就只是总结下java了. TestNG在线安装: 打开Eclipse   Help ->Install New Software ,   然后Add   "http://beust.com/eclipse" 选择TestNG,finish下一步完成安装. 验证是否安装成功 File->new->other 导入sele

Selenium Java WebDriver 使用

一. Firefox安装Selenium插件 在FireFox的菜单中的附加组件中搜索Selenium IDE 然后安装 二. 使用Selenium IDE录制脚本/导出脚本 点击图中标志打开Selenium IDE 红色按钮按下表示正在录制,这时候只用将界面切换到Firefox,网址中输入www.baidu.com,然后再搜索框中输入文字,点击搜索,所有的控件的访问都会被记录下来,然后切换回seleniumIDE就可以看到已经录制完毕 然后在图中红色选中的区域可以调整重新执行的速度,蓝色选中区

selenium+java:获取列表中的值

selenium+java:获取列表中的值 (2011-08-23 17:14:48) 标签: 杂谈 分类: selenium 初步研究利用java+testNg框架下写selenium测试用例,今天学会了几个API:(1)获取页面上列表中的值,并打印输出:System.out.println(selenium.getTable("xpath=/html/body/div[3]/form/table.1.1")); //输出列表中第1行第1列的值(2)判断页面上是否有某个文本:(只能判