简体   繁体   中英

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.

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";
    }
  };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM