我试图使用xpath从活动元素中立即获取数据,但是当我运行项目时,出现了这个错误
线程“main”org.openqa.selenium.staleelementreferenceexception中出现异常:stale元素引用:元素未附加到页面文档
package read;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ResdeStoFromBrowser {
public static final String TEXT_RESET = "\u001B[0m";
public static final String TEXT_RED = "\u001B[31m";
public static final String TEXT_GREEN = "\u001B[32m";
public static final String TEXT_CYAN = "\u001B[36m";
public void ResdeSto() throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\owner\\....\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.navigate().to("https:.........");
driver.manage().window().maximize();
while (true) {
TimeUnit.SECONDS.sleep(1);
String sel2 = driver.findElement(By.xpath("/html/body/div[2]/div[1]/div/div[2]/div[2]/div[2]/div[2]/div[1]/div[1]/span[3]")).getText();
System.out.println(TEXT_GREEN + " " + sel2 + TEXT_RESET + " ");
}
}
}
1条答案
按热度按时间tyg4sfes1#
你写了“我正在尝试立即获取数据…”好吧,这可能是个问题。
StaleElementReferenceException
在网页内容刷新之前或刷新过程中获取web元素时抛出。换句话说,它是过早获得的。解决方案是等待页面完全加载完毕。“元素未附加到页面文档”意味着web元素可能不再位于html文档中。
获取web元素有两种方法:
假设你在正确的页面上,
findElement
将立即尝试定位元件。如果页面在加载过程中,很可能会导致op帖子中提到的错误。解决这个问题的正确方法是添加隐式等待。在上面的片段中,从
implicitlyWait
调用,直到测试会话结束,在尝试获取web元素之前,应用程序将等待传递给函数的最短时间;在我的例子中是10秒。更好的方法是使用
WebDriverWait
班级。WebDriver driver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement button = wait.until(ExpectedConditions.elementToBeClickable(By.xpath(XPATH EXPRESSION HERE)));
button.click();
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.navigate().to("https:.........");
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement button = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("...")));
button.click();
public class TickerPageTest {
@Test
public void printTickerValueEndlessLoop() {
System.setProperty("webdriver.chrome.driver", "F:\Users\Hector\webdriver\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://coincheck.com/exchange/tradeview");
}
span:5898999
...
span:5900895
...
span:5898999
try {
System.out.println(element.getTagName() + ":" + element.getText());
} catch (StaleElementReferenceException e) {
System.err.println("Test lost sync... this will be ignored.");
}
span:5906025
Test lost sync... this will be ignored.
span:5906249