Reputation: 5674
So i'm facing a small perforemence issue while using findElement(By.xpath("..."))
First i'm locating a ul
element that contains around 20 li
child.
by using then on each of the child i'm locating the inner xpath
to the information by using the following:
List<WebElement> addrBookNames = driver.findElements(By.xpath("//ul[@class='displayAddressUL']"));
for(WebElement addr : addrBookNames)
{
String fullName = addr.findElement(By.xpath("li[@class='AddressFullName']/b")).getText();
String addressLine = addr.findElement(By.xpath("li[@class='AddressAddressLine']")).getText();
String city = addr.findElement(By.xpath("li[@class='AddressCity']")).getText();
String county = addr.findElement(By.xpath("li[@class='country']")).getText();
String phoneNumber = addr.findElement(By.xpath("li[@class='phone']")).getText();
}
The above code takes around 5 sec, checked it by using :
double stime = System.currentTimeMillis();
double TotalTime = System.currentTimeMillis() - stime;
before and after.
Is there anything wrong with the way i'm extracting the inner xpaths
from the selected node?
Upvotes: 0
Views: 556
Reputation: 7339
1) I would try as alternative CSS selector approach and create 5 WebElement Lists ( already in split representation for searched fields):
List<WebElement> fullNames = driver.findELements(By.cssSelector("ul.displayAddressUL li.AddressFullName>b"));
List<WebElement> addressLines= driver.findELements(By.cssSelector("ul.displayAddressUL li.AddressAddressLine"));
List<WebElement> cities= driver.findELements(By.cssSelector("ul.displayAddressUL li.AddressCity"));
List<WebElement> countries=driver.findELements(By.cssSelector("ul.displayAddressUL li.country"));
List<WebElement> phoneNums=driver.findELements(By.cssSelector("ul.displayAddressUL li.phone"));
for (int i=0;i<fullNames.size(); i++){
String fullName= fullNames.get(i).getText();
String addressLine =addressLines.get(i).getText();
String city = cities.get(i).getText();
String county = countries.get(i).getText();
String phoneNumber = phoneNums.get(i).getText();
}
Also I'd like to add: CSS selectors perform far better than Xpath and it is well documented in Selenium community. Here are some reasons,
More details on performance comparison you can get here
2) another alternative approach that I would recommend as mentioned here
try to use HtmlUnitDriver
, that will definitely increase your performance;
OR:
to use pure js wrapped by Javascipt executor for text extraction like:
String elem_css_selector="blablabla...";
JavascriptExecutor js = (JavascriptExecutor) driver;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("var x = $(\""+elem_css_selector+"\");");
stringBuilder.append("return x.text().toString();") ;
String resultingText= (String) js.executeScript(stringBuilder.toString());
Assert.assertTrue(resultingText.trim().equals("Expected Text") );
Upvotes: 3