I am trying to automate the Scenario of NSE India https://www.nseindia.com/.

I am trying to capture the Nifty50 increment or decrement value using Xpath as //nobr/span[@class='red'][1] when sensex is down and //nobr/span[@class='green'][1] when sensex is up. I need to handle this dynamic value in one xpath.

I tried with //nobr/span[@class='green' OR @class='red'][1]. This is throwing an error:

Exception in thread "main" org.openqa.selenium.InvalidSelectorException: invalid selector: Unable to locate an element with the xpath expression //nobr/span[@class='green' OR @class='red'][1] because of the following error: SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//nobr/span[@class='green' OR @class='red'][1]' is not a valid XPath expression.

The code:

package testcases;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Nifty_Search {

  public static void main(String[] args) {

    System.setProperty("webdriver.chrome.driver", "B:\\Automation\\software\\chromedriver_win32\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    System.out.println("Normal Market Status :: "+driver.findElement(By.xpath("//span[@id='status1']")).getText().trim());
    System.out.println("Nifty 50 Today's Price :: "+driver.findElement(By.xpath("//p[@class='right']//nobr")).getText().trim());
    System.out.println("Nifty 50 Today's Price Change :: "+driver.findElement(By.xpath("//nobr/span[@class='green' OR @class='red'][1]")).getText().trim());
    System.out.println("Company_Name :: "+driver.findElement(By.xpath("//nobr/span[@class='arrowGreen']")).getText().trim());       
    System.out.println("Nifty 50 Today's Price change Percentage :: "+driver.findElement(By.xpath("//nobr/span[@class='green' OR @class='red'][2]")).getText().trim());

It's just that the case of the XPath operators matters. Change OR to or:

//nobr/span[@class='green' or @class='red'][1]

Note that it would probably a bit more reliable to look for this element in the div with the id="niftyDiv" only since green and red classes are really broad. And, I would switch to a CSS selector instead for a more concise locator:

#niftyDiv nobr > .red,.green

Another reason why prefer CSS selector instead of an XPath is that of the class attribute handling, it is a multi-valued attribute and is naturally addressed in CSS selectors - XPath has no special handling for multi-valued attributes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.