Skip to content

Instantly share code, notes, and snippets.

@monperrus
Created September 21, 2012 13:21
Show Gist options
  • Save monperrus/3761429 to your computer and use it in GitHub Desktop.
Save monperrus/3761429 to your computer and use it in GitHub Desktop.
Table data extraction with Selenium 2
WebDriver webDriver = new FirefoxDriver();
webDriver.navigate().to("http://example.com/some/page");
// simplified: find table which contains the keyword
WebElement tableElement = webDriver.findElement(By.xpath("//table[contains(text(), 'Username')]"));
// create empty table object and iterate through all rows of the found table element
ArrayList<HashMap<String, WebElement>> userTable = new ArrayList<HashMap<String, WebElement>>();
ArrayList<WebElement> rowElements = tableElement.findElements(By.xpath(".//tr"));
// get column names of table from table headers
ArrayList<String> columnNames = new ArrayList<String>();
ArrayList<WebElement> headerElements = rowElements.get(0).findElements(By.xpath(".//th"));
for (WebElement headerElement: headerElements) {
columnNames.add(headerElement.getText());
}
// iterate through all rows and add their content to table array
for (WebElement rowElement: rowElements) {
HashMap<String, WebElement> row = new HashMap<String, WebElement>();
// add table cells to current row
int columnIndex = 0;
ArrayList<WebElement> cellElements = rowElement.findElements(By.xpath(".//td"));
for (WebElement cellElement: cellElements) {
row.put(columnNames.get(columnIndex), cellElement);
columnIndex++;
}
userTable.add(row);
}
// finally fetch the desired data
WebElement cellInSecondRowFourthColumn = userTable.get(1).get("Email");
@soniika
Copy link

soniika commented Dec 1, 2015

Can you please tell how to write a web table data into excel using poi

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment