Nexion21 Nexion21 - 1 month ago 8
HTML Question

How can I extract the text from a variable with Selenium WebDriver?

If I use "Inspect Element" on FireFox, I see this:

<span class="stock-number-value ng-binding">17109 </span>


When I use driver.getSource(), that 17109 is replaced by "vehicle.attributes.stockNumber".

My main goal is to use the driver to get whatever value is stored by vehicle.attributes.stockNumber, but I can't figure out how to get the contents of that variable using Selenium.

Answer

I suspect you are getting the source too early in the process while the angular is not yet ready and the bindings are not yet data-feeded. I'd use a custom wait condition function to wait for the "stock" to have a numeric value:

WebDriverWait wait = new WebDriverWait(webDriver, 510);
WebElement stock = wait.until(waitForStock(By.cssSelector(".stock-number-value")));
System.out.println(stock.getText());

where waitForStock is something along these lines:

public static ExpectedCondition<Boolean> waitForStock(final By locator) {
  return new ExpectedCondition<Boolean>() {
    @Override
    public Boolean apply(WebDriver driver) {
      try {
        WebElement elm = driver.findElement(locator);
        return elm.getText().trim().matches("[0-9]+");
      } catch (NoSuchElementException e) {
        return false;
      } catch (StaleElementReferenceException e) {
        return false;
      }
    }

    @Override
    public String toString() {
      return "stock is not yet loaded";
    }
  };
}