Blogs

How to handle class name with spaces in it – CPSAT Blog series 1

 

Let us look at an example.
Please look at the following page from a website – flipkart.com
Steps performed to reach to this place

  1. Search for Samsung mobiles
  2. Click on price high to low


 
we have tried to inspect the price element using chrome browser.
The html code snippet for this element is shown below
<div class=”_1vC4OE _2rQ-NK”>₹84,900</div>
If we were to use xpath and css as locator for this element – it does not give a problem.
We are trying use class name in this case, If you note there is space in between, _1vC4OE and _2rQ-NK
Please note that the class name has space in between the two colored parts, green part and the yellow part.
If we were to use the class name as a locator using selenium the sample code that we can first think of will be as below.
[gdlr_code title=”Sample code for locating an element using class name having spaces” active=”yes”]
By priceLocator = By.className(“_1vC4OE _2rQ-NK”);
WebElement priceElement = driver.findElement(priceLocator);
String strPrice = priceElement.getText();
System.out.println(strPrice);
[/gdlr_code]
When we try to run the above code after adding proper selenium code before it, it actually gives an exception.
*** Element info: {Using=class name, value=_1vC4OE _2rQ-NK}
       at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
       at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
       at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
       at java.lang.reflect.Constructor.newInstance(Unknown Source)
       at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
       at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
       at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
       at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:363)
       at org.openqa.selenium.remote.RemoteWebDriver.findElementByClassName(RemoteWebDriver.java:477)
       at org.openqa.selenium.By$ByClassName.findElement(By.java:391)
       at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:355)
The code with this sample code is as below, please note this code is going to show the exception above, we will be solving this problem shortly.
[gdlr_code title=”Sample code which throws exception when using class names with spaces ” active=”no”]
package cpsatblog;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
/**
* @author CP-SAT BLOG SERIES
* How to handle spaces in a class name – this example shows the exception
*
*/
public class HowToHandleWhiteSpaceInClassError {
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver driver;
/**
* set the chromedriver
* set implicit wait for 20 seconds
* open the required website
*/
System.setProperty(“webdriver.chrome.driver”,”.//test//resources//drivers//chromedriver.exe”);
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get(“https://www.flipkart.com/”);
/**
* close the opening dialog box
* clear the search field
* search for samsung mobiles
* click on price high to low
*/
driver.findElement(By.xpath(“//*[@id=’container’]/following-sibling::div/div/div/button”)).click();
driver.findElement(By.name(“q”)).clear();
driver.findElement(By.name(“q”)).sendKeys(“Samsung Mobile”);
driver.findElement(By.name(“q”)).sendKeys(Keys.ENTER);
driver.findElement(By.xpath(“//div[text()=’Price — High to Low’]”)).click();
/**
* we want to read the maximum price of a mobile phone from samsung
* <div class=”_1vC4OE _2rQ-NK”>₹84,900</div>
*/
By priceLocator = By.className(“_1vC4OE _2rQ-NK”);
WebElement priceElement = driver.findElement(priceLocator);
String strPrice = priceElement.getText();
System.out.println(strPrice);
}
}
[/gdlr_code]
The reason the code gives a problem is because this class name does not exist, infact these are actually two separate classes. As soon as there is a space each word is considered to be a different class.
Class 1 = _1vC4OE
Class 2 = _2rQ-NK
In order to handle this, we would need to actually use the following code snippets

  • Following would work – cssSelector(“div[class=’_1vC4OE _2rQ-NK’]”);

[gdlr_code title=”Solution 1 Snippet– how to handle space in class name” active=”yes”]
   // solution 1 – how to handle space in class name
      //<div class=”_1vC4OE _2rQ-NK”>₹84,900</div>
By priceLocator1 = By.cssSelector(“div[class=’_1vC4OE _2rQ-NK’]”);
WebElement priceElement1 = driver.findElement(priceLocator1);
String strPrice = priceElement1.getText();
System.out.println(“sol1 worked ” + strPrice);
[/gdlr_code]

  • Following would also work – cssSelector(“div._1vC4OE._2rQ-NK”);

[gdlr_code title=”Solution 2 Snippet– how to handle space in class name” active=”yes”]
// solution 2 – how to handle space in class name
By priceLocator2 = By.cssSelector(“div._1vC4OE._2rQ-NK”);
WebElement priceElement2 = driver.findElement(priceLocator2);
String strPrice2 = priceElement2.getText();
System.out.println(“sol2 worked ” +strPrice2);
[/gdlr_code]

  • Following would also work – xpath(“//div[@class=’_1vC4OE _2rQ-NK’]”);

[gdlr_code title=”solution 3 – how to handle space in class name” active=”yes”]
// solution 3 – how to handle space in class name
By priceLocator3 = By.xpath(“//div[@class=’_1vC4OE _2rQ-NK’]”);
WebElement priceElement3 = driver.findElement(priceLocator3);
String strPrice3 = priceElement3.getText();
System.out.println(“sol3 worked ” +strPrice3);
[/gdlr_code]

  • Following would also work – xpath(“//div[contains(@class, ‘_1vC4OE’) and contains(@class, ‘_2rQ-NK’)]”);

[gdlr_code title=”solution 4 – how to handle space in class name” active=”yes”]
  // solution 4 – how to handle space in class name
By priceLocator4 = By.xpath(“//div[contains(@class, ‘_1vC4OE’) and contains(@class, ‘_2rQ-NK’)]”);
WebElement priceElement4 = driver.findElement(priceLocator4);
String strPrice4 = priceElement4.getText();
System.out.println(“sol4 worked ” +strPrice4);
[/gdlr_code]
 
Here is the entire working code
[gdlr_code title=”Complete working code” active=”YES”]
package cpsatblog;
 
import java.util.List;
import java.util.concurrent.TimeUnit;
 
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
/**
 * @author CP-SAT BLOG SERIES
 * How to handle spaces in a class name
 *
 */
public class HowToHandleWhiteSpaceInClass {
 
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver driver;
 
/**
             * set the chromedriver
             * set implicit wait for 20 seconds
             * open the required website
             */
System.setProperty(“webdriver.chrome.driver”,”.//test//resources//drivers//chromedriver.exe”);
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get(“https://www.flipkart.com/”);
 
/**
             * close the opening dialog box
             * clear the search field
             * search for samsung mobiles
             * click on price high to low
             */
driver.findElement(By.xpath(“//*[@id=’container’]/following-sibling::div/div/div/button”)).click();
driver.findElement(By.name(“q”)).clear();
driver.findElement(By.name(“q”)).sendKeys(“Samsung Mobile”);
driver.findElement(By.name(“q”)).sendKeys(Keys.ENTER);
driver.findElement(By.xpath(“//div[text()=’Price — High to Low’]”)).click();
 
// let the page load
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
    /**
             * we want to read the maximum price of a mobile phone from samsung
             * <div class=”_1vC4OE _2rQ-NK”>₹84,900</div>
             */
   // solution 1 – how to handle space in class name
            //<div class=”_1vC4OE _2rQ-NK”>₹84,900</div>
By priceLocator1 = By.cssSelector(“div[class=’_1vC4OE _2rQ-NK’]”);
WebElement priceElement1 = driver.findElement(priceLocator1);
String strPrice = priceElement1.getText();
System.out.println(“sol1 worked ” + strPrice);
 
  // solution 2 – how to handle space in class name
By priceLocator2 = By.cssSelector(“div._1vC4OE._2rQ-NK”);
WebElement priceElement2 = driver.findElement(priceLocator2);
String strPrice2 = priceElement2.getText();
System.out.println(“sol2 worked ” +strPrice2);
// solution 3 – how to handle space in class name
By priceLocator3 = By.xpath(“//div[@class=’_1vC4OE _2rQ-NK’]”);
WebElement priceElement3 = driver.findElement(priceLocator3);
String strPrice3 = priceElement3.getText();
System.out.println(“sol3 worked ” +strPrice3);
 
         // solution 4 – how to handle space in class name
By priceLocator4 = By.xpath(“//div[contains(@class, ‘_1vC4OE’) and contains(@class, ‘_2rQ-NK’)]”);
WebElement priceElement4 = driver.findElement(priceLocator4);
String strPrice4 = priceElement4.getText();
System.out.println(“sol4 worked ” +strPrice4);
driver.quit();
}
}
[/gdlr_code]
Please note that, this blog is part of CPSAT blog series, if you want to contribute here, please get in touch with us.
#CPSAT is the #only #globally #recognized #practical #assessment #driven #selenium #certification.
To know more about upcoming CPSAT events, please visit the following websites
https://ataevents.agiletestingalliance.org/
https://cpsat.agiletestingalliance.org/index.html
Good luck for your selenium learnings.
best wishes,
CPSAT Team

Leave a Comment