Getting value from data-value (webdriver selenium / java)



  • I have the following HTML code

    08
    09

    I would like to extract the value of data-val="9" and assign it to a String variable.

    I tried

    driver.findElement(By.xpath("//div[@role='option']//*[@tabindex = '0']")).getText();
    

    and I am getting "Unable to locate element"

    Hope to have advice. Thanks



  • I checked your HTML code and the java code. I have found a few issues in the codes.

    In this line above the Xpath is wrong and hence you are getting the error Unable to locate element".

    Here is the correct xpath you can use: //div[@role='option' and @tabindex='0']

    Here is my HTML with which I tested:

    
    
    
    
    
        
    08
    09

    Here is my Java + Selenium code which worked for me:

    try {
        WebDriver driver;
        System.setProperty("webdriver.gecko.driver", System.getProperty("user.dir") + "//geckodriver");
        System.setProperty(FirefoxDriver.SystemProperty.BROWSER_LOGFILE, "FFLogs.txt");
        driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        driver.get("http://localhost/1");
        driver.manage().window().maximize();
        Thread.sleep(2000);
        String text = driver.findElement(By.xpath("//div[@role='option' and @tabindex='0']")).getText();
        System.out.println("Your string: " + text);
        String text1 = driver.findElement(By.xpath("//div[@role='option' and @tabindex='0']")).getAttribute("data-val");
        System.out.println("Your attribute: " + text1);
    
    Thread.sleep(5000);
    driver.close();
    

    } catch (Exception e) {
    e.printStackTrace();
    }




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2