Xpath 是正确的仍然没有这样的元素:无法定位元素

Xpath is correct still get no such element: Unable to locate element

我的 Xpath 是正确的,没有 iFrame,我可以在 Chrome 控制台中找到元素,但我的程序仍然失败。我也使用过显式等待。

网站http://newtours.demoaut.com/ 我正在尝试找到登录页面并发送登录 ID。

错误信息:

PASSED: openURL FAILED: loginToTours **org.openqa.selenium.NoSuchElementException**: **no such element: Unable to locate element: {"method":"xpath","selector":"//input[@name='userName']"}** *** Element info: {Using=xpath, value=//input[@name='userName']}
 package SeleniumPracticePackage;
 import org.openqa.selenium.By;
 import org.openqa.selenium.WebDriver;
 import org.openqa.selenium.WebElement;
 import org.openqa.selenium.chrome.ChromeDriver;
  import org.openqa.selenium.chrome.ChromeOptions;
 import org.openqa.selenium.support.ui.ExpectedConditions;
 import org.openqa.selenium.support.ui.WebDriverWait ;
 import java.io.FileInputStream;
 import java.io.IOException;
 import java.util.List;
 import java.util.Properties;
 import org.testng.annotations.BeforeTest;
 import org.testng.annotations.Parameters;
 import org.testng.annotations.Test;

 public class CallUrl {

WebDriver driver;
Properties prop;    

@BeforeTest
public void openBrowser() throws IOException
{

// driver = new ChromeDriver();

 ChromeOptions options = new ChromeOptions();
 options.addArguments("chrome.switches","--disable-extensions");
 System.setProperty("webdriver.chrome.driver","C:\Users\Ashish\Documents\Selenium\drivers\chromedriver_win32\chromedriver.exe");
 //System.setProperty("webdriver.chrome.driver",(System.getProperty("user.dir") + "//src//test//resources//chromedriver_new.exe"));
 driver = new ChromeDriver(options);     
}
@Test
public void openURL() throws IOException
{
//call URL from properties file
 prop = new Properties();
FileInputStream urlFile = new FileInputStream("C:\Users\Ashish\Documents\Selenium\SeleniumPracticeSite\src\URL.properties");
prop.load(urlFile); 
driver.get(prop.getProperty("URL"));
WebDriverWait myDynamicElement = new WebDriverWait(driver,30);
myDynamicElement.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//input[@name='userName']")));
}

@Test       
public void loginToTours () throws InterruptedException
{

  driver.findElement(By.xpath("//input[@name='userName']")).click();
  //sendKeys(prop.getProperty("login"));

}   

}

TestNG XML

<?xml version="1.0" encoding="UTF-8"?>
  <suite name = "Automation Practice Test">
    <test name ="smoke test">  
      <groups>
        <run>
          <include name="Priority2" />
        </run>
      </groups>
         <classes>
            <class name ="SeleniumPracticePackage.CallUrl" />
         </classes>
       </test>
   </suite> 

网站HTML源代码

                 <tr>
                  <td align="right"><font face="Arial, Helvetica, sans-serif" size="2">User 
                    Name: </font></td>
                  <td width="112">
                    <input type="text" name="userName" size="10">
                  </td>
                </tr>

您的 XPath 正在搜索一个 input 标记,该标记不在您的 XML 中。

问题出在你的测试代码上

说明:您的测试 class 中有两个 @Test 方法。其中一个打开 URL 并等待元素出现,另一个方法只搜索元素。如果 TestNG 首先结束 运行 您的 loginToTours() 测试方法,那么您将看到此错误消息。默认情况下,TestNG 按字母顺序执行方法。由于 loginToTours() 没有指定 findElement() 位于哪个网页,Selenium 最终在空白页面上执行它,因此您会看到错误消息。修复方法之一是让 loginToTours() 方法依赖于 openURL(),这样在搜索发生之前已经在浏览器中打开了一个有效的网页。 [这也正是我在清理后的代码中所做的]。

WebDriver 在这里没有错:)

这是您测试代码的清理版本,可以正常工作

public class CallUrl {
    WebDriver driver;

    @BeforeClass
    public void openBrowser() throws IOException {
        ChromeOptions options = new ChromeOptions();
        options.addArguments("chrome.switches", "--disable-extensions");
        driver = new ChromeDriver(options);
    }

    @AfterClass
    public void cleanup() {
        if (driver != null) {
            driver.quit();
        }
    }

    @Test
    public void openURL() throws IOException {
        driver.get("http://newtours.demoaut.com/");
        WebDriverWait myDynamicElement = new WebDriverWait(driver, 30);
        myDynamicElement.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//input[@name='userName']")));
    }

    @Test (dependsOnMethods = "openURL")
    public void loginToTours() throws InterruptedException {
        driver.findElement(By.xpath("//input[@name='userName']")).click();
    }

}

我遇到了类似的问题,即使 XPath 有效(当进入检查模式时它能够找到元素),我也没有得到值。我的代码看起来有点像下面 -

driver.get("https://www.theurlgoeshere")
elements = driver.find_elements_by_xpath("//*[@class='classname']")
for element in elements:
    element.send_keys("Test value")
driver.close()

对于上面的代码,我遇到了找不到元素的错误。为了避免这个错误,我导入了“时间”模块,并在get语句后添加了一个睡眠时间,通过这个小修改代码就可以了。

driver.get("https://www.theurlgoeshere")
time.sleep(3)
elements = driver.find_elements_by_xpath("//*[@class='classname']")
for element in elements:
element.send_keys("Test value")
driver.close()

随着并行处理的进行,驱动程序甚至在 class 出现在动态页面上之前就试图找到它。在搜索其中的 XPath 之前,页面必须完全加载。