Created
September 21, 2012 13:21
-
-
Save monperrus/3761429 to your computer and use it in GitHub Desktop.
Table data extraction with Selenium 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can you please tell how to write a web table data into excel using poi