Tuesday, February 16, 2016

Working with WebTable

Go to This site http://www.espncricinfo.com/south-africa-v-pakistan-2013/engine/match/567363.html

and display all the players information and also get the total runs count
Background : Most of the time in selenium its pretty hard to automate tables that are in tr/td format.


For understanding the webtable please visit :  http://www.w3schools.com/html/html_tables.asp

public class WebTable {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
WebDriver driver = new FirefoxDriver();
driver.get("http://www.espncricinfo.com/south-africa-v-pakistan-2013/engine/match/567363.html");
// wait for 5 sec
Thread.sleep(5000);
String start="//*[@id='full-scorecard']/div[2]/div/table[1]/tbody/tr[";
String end = "]/td[4]";
int total=0;
for (int i=2;i<=24;i=i+2){
System.out.println(driver.findElement(By.xpath(start+i+end)).getText());
String x = driver.findElement(By.xpath(start+i+end)).getText();
//x= 24; 30
// covert string to integer...
total = total + Integer.parseInt(x); // total = 0 +24
}
String expected = "253";
int asexpected = Integer.parseInt(expected);
System.out.println(total);
if (total == asexpected){
System.out.println("PASS");
}else{
System.out.println("FAIL");
}
String gstart="//*[@id='full-scorecard']/div[2]/div/table[1]/tbody/tr[";
String mid="]/td[";
String gend="]";
for (int rownum=2;rownum<;=24;rownum=rownum+2){
for(int col=2;col<=9;col++){
System.out.println(driver.findElement(By.xpath(gstart+rownum+mid+col+gend)).getText());
}
// print next line...
System.out.println();
}
//*[@id="full-scorecard"]/div[2]/div/table[1]/tbody/tr[2]/td[1]/img
driver.findElement(By.xpath("//*[@id='full-scorecard']/div[2]/div/table[1]/tbody/tr[2]/td[1]/img")).click();
}
}
view raw WebTable.java hosted with ❤ by GitHub




Output :

GC Smith*
c †Sarfraz Ahmed b Umar Gul
24
96
59
2
0
40.67

AN Petersen
c Mohammad Hafeez b Junaid Khan
20
91
53
2
0
37.73

HM Amla
c Azhar Ali b Younis Khan
37
112
67
6
0
55.22

JH Kallis
c Asad Shafiq b Umar Gul
50
82
78
9
0
64.10

AB de Villiers†
c †Sarfraz Ahmed b Mohammad Hafeez
31
124
84
3
0
36.90

F du Plessis
b Junaid Khan
41
131
107
2
0
38.31

D Elgar
c †Sarfraz Ahmed b Mohammad Hafeez
27
54
40
3
1
67.50

RJ Peterson
b Mohammad Hafeez
0
17
11
0
0
0.00

VD Philander
run out (Asad Shafiq/†Sarfraz Ahmed)
1
11
2
0
0
50.00

DW Steyn
not out
12
11
10
1
1
120.00

M Morkel
b Mohammad Hafeez
0
7
2
0
0
0.00

Extras
(b 4, lb 4, w 1, nb 1)
10