【问题标题】:How can I extract the text from a variable with Selenium WebDriver?如何使用 Selenium WebDriver 从变量中提取文本?
【发布时间】:2017-03-21 06:14:46
【问题描述】:

如果我在 FireFox 上使用“检查元素”,我会看到:

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

当我使用 driver.getSource() 时,17109 被“vehicle.attributes.stockNumber”替换。

我的主要目标是使用驱动程序获取 vehicle.attributes.stockNumber 存储的任何值,但我不知道如何使用 Selenium 获取该变量的内容。

【问题讨论】:

    标签: java html selenium selenium-webdriver


    【解决方案1】:

    我怀疑您在处理过程中过早获取源代码,而 angular 尚未准备好 并且绑定尚未提供数据。我会使用自定义等待条件函数来等待“股票”有一个数值:

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

    waitForStock 是这样的:

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

    【讨论】:

    • 完美,我以前从未使用过 WebDriverWait 对象。感谢您定义“elm.getText().trim().matches("[0-9]+");”还有,你为我节省了一些时间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-19
    • 2014-06-29
    相关资源
    最近更新 更多