【问题标题】:java selenium phantomjs can't locate element by xpathjava selenium phantomjs无法通过xpath定位元素
【发布时间】:2017-07-13 23:13:22
【问题描述】:

提交的代码仅用于证明 PhantomJS 与 Selenium 的使用概念。

我正在测试一个单页应用程序。

代码在 GoogleChrome 和 FireFox 上运行良好,但在 PhantomJS 中找不到元素。

问题是 驱动程序在登录页面上找到“登录”按钮(通过 xpath)但是当用户在登录表单上重定向时尝试通过xpath 定位元素后抛出TimeoutException:ExpectedCondition failed

我正在使用:

  • 硒 3.4.0
  • PhantomJS 2.1.1

我的代码:

public class GoogleSearchTest 
{

private WebDriver driver;
private WebDriverWait wait;

@Before 
public void SetUp()
{
    System.setProperty("phantomjs.binary.path", "./src/test/resources/drivers/phantomjs.exe");
    driver = new PhantomJSDriver();
    driver.manage().window().maximize();
    driver.get("https://dev.investmentpunk.academy");
    wait = new WebDriverWait(driver, 10);
}
@Test
public void testGoogleSearch() throws InterruptedException
{
    WebElement Login_btn = driver.findElement(By.xpath("//ul/li[@class='ng-scope'][1]"));
    Login_btn.click();

    wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@class='c-input-db ng-pristine ng-untouched ng-empty ng-invalid ng-invalid-required ng-valid-minlength ng-valid-maxlength']"))).sendKeys("user1");

    WebElement Password = driver.findElement(By.xpath("//div[@class='form-row'][2]/input[@class='c-input-db ng-pristine ng-untouched ng-empty ng-invalid ng-invalid-required']"));
    Password.sendKeys("qwerty");

    WebElement Login = driver.findElement(By.xpath("//button[@class='btn btn-blue']"));
    Login.click();
}

@After
public void tearDown()
{
    driver.quit();
}

请帮我解决这个问题。

======================编辑部分======================

所以,情况是我正在使用您的 xpathes 使用 TestNG(或使用 JUnit)运行代码,并且它一直有效,直到昨天。因此,驱动程序无法找到 WebElement Login_btn = driver.findElement(By.xpath("//ul/li[@class='ng-scope']/a[text()='EINLOGGEN']")); 我没有在代码中提供任何重大更改:

public class GoogleSearchTest 
{   
private WebDriver driver;
private WebDriverWait wait;

//second commit mess

@BeforeTest
public void SetUp()
{
    System.setProperty("phantomjs.binary.path", "E:/PhantomJS/phantomjs-2.1.1-windows/bin/phantomjs.exe");
    driver = new PhantomJSDriver();
    System.out.println("=====PhantomJS Driver Initiated=====");
    driver.manage().window().maximize();
    driver.get("https://dev.investmentpunk.academy/");
    System.out.println("=====URL Accessed=====");
    wait = new WebDriverWait(driver, 10);
}

@Test
public void testGoogleSearch() throws InterruptedException
{       
    WebElement Login_btn = driver.findElement(By.xpath("//ul/li[@class='ng-scope']/a[text()='EINLOGGEN']"));
    Login_btn.click();
    System.out.println("=====EINLOGGEN button Clicked=====");

    wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@placeholder='Username/Email']"))).sendKeys("user1");
    System.out.println("=====Username Sent=====");

    WebElement Password = driver.findElement(By.xpath("//input[@placeholder='Passwort']"));
    Password.sendKeys("qwerty");
    System.out.println("=====Password Sent=====");

    WebElement Login = driver.findElement(By.xpath("//button[@class='btn btn-blue']"));
    Login.click();
    System.out.println("=====Login button Clicked=====");
}

@AfterTest
public void tearDown()
{
    driver.quit();
}

}

Fist error screenshot

Second error screenshot

【问题讨论】:

    标签: java selenium phantomjs single-page-application


    【解决方案1】:

    这是您问题的答案:

    关于解决方案的几句话:

    1. 您构造的xpath 包含索引。所以它们很脆弱。
    2. 就像class 属性一样,我们也可以使用placeholder 属性。
    3. 您使用了来自JUnit@Before@After 注释,而我使用了来自TestNG@BeforeTest@AfterTest 注释,并且下面的代码块工作正常:

      public class Q44928902_GoogleSearchTest 
      {
      
          private WebDriver driver;
          private WebDriverWait wait;
      
          @BeforeTest 
          public void SetUp()
          {
              System.setProperty("phantomjs.binary.path", "C:/Utility/phantomjs-2.1.1-windows/bin/phantomjs.exe");
              driver = new PhantomJSDriver();
              System.out.println("=====PhantomJS Driver Initiated=====");
              driver.manage().window().maximize();
              driver.get("https://dev.investmentpunk.academy");
              System.out.println("=====URL Accessed=====");
              wait = new WebDriverWait(driver, 10);
          }
          @Test
          public void testGoogleSearch() throws InterruptedException
          {
              WebElement Login_btn = driver.findElement(By.xpath("//ul/li[@class='ng-scope']/a[contains(@href,'/db/login/')][text()='EINLOGGEN']"));
              Login_btn.click();
              System.out.println("=====EINLOGGEN button Clicked=====");
      
              wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@placeholder='Username/Email']"))).sendKeys("user1");
              System.out.println("=====Username Sent=====");
      
              WebElement Password = driver.findElement(By.xpath("//input[@placeholder='Passwort']"));
              Password.sendKeys("qwerty");
              System.out.println("=====Password Sent=====");
      
              WebElement Login = driver.findElement(By.xpath("//button[@class='btn btn-blue']"));
              Login.click();
              System.out.println("=====Login button Clicked=====");
          }
      
          @AfterTest
          public void tearDown()
          {
              driver.quit();
          }
      }
      
    4. 这是代码块的输出:

      =====PhantomJS Driver Initiated=====
      =====URL Accessed=====
      =====EINLOGGEN button Clicked=====
      =====Username Sent=====
      =====Password Sent=====
      =====Login button Clicked=====
      [INFO  - 2017-07-06T09:58:41.996Z] ShutdownReqHand - _handle - About to shutdown
      PASSED: testGoogleSearch
      
      ===============================================
          Default test
          Tests run: 1, Failures: 0, Skips: 0
      ===============================================
      

    如果这能回答您的问题,请告诉我。


    更新 [07/13/2017 - 19:00 IST]

    我重新运行了相同的代码,结果如下:

    Jul 13, 2017 6:56:42 PM org.openqa.selenium.phantomjs.PhantomJSDriverService <init>
    INFO: executable: C:\Utility\phantomjs-2.1.1-windows\bin\phantomjs.exe
    Jul 13, 2017 6:56:42 PM org.openqa.selenium.phantomjs.PhantomJSDriverService <init>
    INFO: port: 13867
    Jul 13, 2017 6:56:42 PM org.openqa.selenium.phantomjs.PhantomJSDriverService <init>
    INFO: arguments: [--webdriver=13867, --webdriver-logfile=C:\Users\AtechM_03\LearnAutmation\LearnAutomationTestNG\phantomjsdriver.log]
    Jul 13, 2017 6:56:42 PM org.openqa.selenium.phantomjs.PhantomJSDriverService <init>
    INFO: environment: {}
    [INFO  - 2017-07-13T13:26:45.068Z] GhostDriver - Main - running on port 13867
    [INFO  - 2017-07-13T13:26:46.224Z] Session [eb077d70-67ce-11e7-9bc6-6935b23fd504] - page.settings - {"XSSAuditingEnabled":false,"javascriptCanCloseWindows":true,"javascriptCanOpenWindows":true,"javascriptEnabled":true,"loadImages":true,"localToRemoteUrlAccessEnabled":false,"userAgent":"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/538.1 (KHTML, like Gecko) PhantomJS/2.1.1 Safari/538.1","webSecurityEnabled":true}
    [INFO  - 2017-07-13T13:26:46.224Z] Session [eb077d70-67ce-11e7-9bc6-6935b23fd504] - page.customHeaders:  - {}
    [INFO  - 2017-07-13T13:26:46.224Z] Session [eb077d70-67ce-11e7-9bc6-6935b23fd504] - Session.negotiatedCapabilities - {"browserName":"phantomjs","version":"2.1.1","driverName":"ghostdriver","driverVersion":"1.2.0","platform":"windows-8-32bit","javascriptEnabled":true,"takesScreenshot":true,"handlesAlerts":false,"databaseEnabled":false,"locationContextEnabled":false,"applicationCacheEnabled":false,"browserConnectionEnabled":false,"cssSelectorsEnabled":true,"webStorageEnabled":false,"rotatable":false,"acceptSslCerts":false,"nativeEvents":true,"proxy":{"proxyType":"direct"}}
    [INFO  - 2017-07-13T13:26:46.225Z] SessionManagerReqHand - _postNewSessionCommand - New Session Created: eb077d70-67ce-11e7-9bc6-6935b23fd504
    Jul 13, 2017 6:56:46 PM org.openqa.selenium.remote.ProtocolHandshake createSession
    INFO: Detected dialect: OSS
    =====PhantomJS Driver Initiated=====
    =====URL Accessed=====
    =====EINLOGGEN button Clicked=====
    =====Username Sent=====
    =====Password Sent=====
    =====Login button Clicked=====
    [INFO  - 2017-07-13T13:27:05.036Z] ShutdownReqHand - _handle - About to shutdown
    PASSED: testGoogleSearch
    
    ===============================================
        Default test
        Tests run: 1, Failures: 0, Skips: 0
    ===============================================
    
    
    ===============================================
    Default suite
    Total tests run: 1, Failures: 0, Skips: 0
    ===============================================
    
    [TestNG] Time taken by org.testng.reporters.EmailableReporter2@47caedad: 9 ms
    [TestNG] Time taken by org.testng.reporters.XMLReporter@126253fd: 16 ms
    [TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@1807f5a7: 246 ms
    [TestNG] Time taken by org.testng.reporters.jq.Main@415b0b49: 151 ms
    [TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 0 ms
    [TestNG] Time taken by org.testng.reporters.JUnitReportReporter@642a7222: 65 ms
    

    让我确切知道您在哪一行遇到问题,同时更新问题区域中的完整代码和错误堆栈跟踪。

    【讨论】:

    • 谢谢!你的回答帮助了我。我发现真的很有趣,你如何为 web 元素构建一个 xpath。我个人在 Chrome 中使用“XPath helper”插件。您能否提供一些资源,如何构建不会“脆弱”和“脆弱”的 xpath?
    • 好消息!!! IMO,最大的学习资源是阅读他人的代码并帮助他人:) 谢谢
    • 您好!我又遇到了同样的问题。 (今天)即使有你的建议,它也停止了工作。现在它甚至无法通过 xpath 找到第一个元素 (Login_btn) 你能重新运行你的代码吗?我只是想知道,这个问题是与 PhantomJS 相关,还是与 web-application 相关。
    • @DDenys 在我的答案中查看我的更新。谢谢
    • 感谢您的回复。我已经更新了我的帖子。(编辑部分)
    猜你喜欢
    • 1970-01-01
    • 2019-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多