首页 > 解决方案 > Selenium 总是给出 org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element:

问题描述

文字“恭喜!” 只有在交易成功时才会出现在网站上。

我正在尝试使用 JavascriptExecutor 捕获此元素的文本,因为类型设置为隐藏但 selenium 始终显示:

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//div[@class='form-header']//div[contains(text(),'Congratulations')]"}
  (Session info: chrome=85.0.4183.121)

代码 1(不工作)

WebElement ele = driver.findElement(By.xpath(//div[@class='form-header']//div[contains(text(),'Congratulations')]));
JavascriptExecutor js = (JavascriptExecutor)driver;
String text = (String)js.executeScript("return arguments[0].value",ele);
System.out.println(text);

代码 2(不工作)

WebElement ele = driver.findElement(By.xpath(//div[@class='form-header']//div[contains(text(),'Congratulations')]));
    JavascriptExecutor js = (JavascriptExecutor)driver;
    String text = (String)js.executeScript("return arguments[0].innerHTML",ele);
System.out.println(text);

这部分的HTML代码如下:

<input id="hdnWindowLocationHost" name="hdnWindowLocationHost" type="hidden" value="/" data-value="themes/custom">
<div id="sgw" class="sgw SGW-header">
             
        </div>
<div class="page">
        <div class="content">
            <div class="form">
                <div class="form-header">
                    <div class="headline">Congratulations!</div>
                    Your password has been reset. Please log in below with your Username and password.
                </div>

标签: seleniumselenium-webdriver

解决方案


由于元素是动态元素,因此要识别您需要诱导WebDriverWait的元素visibilityOfElementLocated(),您可以使用以下任一Locator Strategies

  • 使用cssSelector

    System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div.form-header > div"))).getText());
    
  • 使用xpathtext()

    System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@class='form-header']/div[text()='Congratulations!']"))).getText());
    
  • 使用xpathcontains()

    System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@class='form-header']/div[contains(., 'Congratulations')]"))).getText());
    

推荐阅读