Java 如何使用SeleniumWebDriver从变量中提取文本?
如果我在FireFox上使用“Inspect Element”,我会看到:Java 如何使用SeleniumWebDriver从变量中提取文本?,java,html,selenium,selenium-webdriver,Java,Html,Selenium,Selenium Webdriver,如果我在FireFox上使用“Inspect Element”,我会看到: 17109 当我使用driver.getSource()时,17109将替换为“vehicle.attributes.stockNumber” 我的主要目标是使用驱动程序获取vehicle.attributes.stockNumber存储的任何值,但我不知道如何使用Selenium获取该变量的内容。我怀疑您在获取源代码的过程中太早,而角度尚未准备好,绑定尚未提供数据。我将使用自定义等待条件函数来等待“股票”具有数值: W
17109
当我使用driver.getSource()时,17109将替换为“vehicle.attributes.stockNumber”
我的主要目标是使用驱动程序获取vehicle.attributes.stockNumber存储的任何值,但我不知道如何使用Selenium获取该变量的内容。我怀疑您在获取源代码的过程中太早,而角度尚未准备好,绑定尚未提供数据。我将使用自定义等待条件函数来等待“股票”具有数值:
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";
}
};
}
公共静态预期条件waitForStock(最终由定位器确定){
返回新的ExpectedCondition(){
@凌驾
公共布尔应用(WebDriver驱动程序){
试一试{
WebElement elm=driver.findElement(定位器);
返回elm.getText().trim().matches(“[0-9]+”);
}捕获(无接触元素例外e){
返回false;
}捕获(StaleElementReferenceException e){
返回false;
}
}
@凌驾
公共字符串toString(){
返回“库存尚未加载”;
}
};
}
Perfect,我以前从未使用过WebDriverWait对象。感谢您定义“elm.getText().trim().matches(“[0-9]+””);此外,您还为我节省了一些时间。