【问题标题】:Selenium "Element not found" due to incorrect XPATH由于 XPATH 不正确,硒“找不到元素”
【发布时间】:2014-11-16 13:14:23
【问题描述】:

我对 Selenium 和 XPath 完全陌生。今天是我第一次尝试使用 Selenium RC 执行一个简单的脚本。请在下面找到代码。

package com.rcdemo;

import org.junit.Test;
import org.openqa.selenium.By;

import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;

public class MathTest {

    @SuppressWarnings("deprecation")
    public static void main(String[] args) throws InterruptedException {

        //Instatiate the RC Server
        Selenium selenium = new DefaultSelenium("localhost", 4444 , "*firefox C:/Program Files (x86)/Mozilla Firefox/firefox.exe", "http://www.calculator.net");
        selenium.start();   // Start
        selenium.open("/");  // Open the URL
        selenium.windowMaximize();

        // Click on Link Math Calculator
        selenium.click("xpath=.//*[@id='menu']/div[3]/a");
        Thread.sleep(4500); // Wait for page load

        // Click on Link Percent Calculator
        selenium.click("xpath=//*[@id='content']/ul/li[3]/a");
        Thread.sleep(4000); // Wait for page load


        // Focus on text Box
        selenium.focus("name=cpar1");
        // enter a value in Text box 1
        selenium.type("css=input[name=\"cpar1\"]", "10");

        // enter a value in Text box 2
        selenium.focus("name=cpar2");
        selenium.type("css=input[name=\"cpar2\"]", "50");

        // Click Calculate button
        selenium.click("xpath=.//*[@id='content']/table/tbody/tr/td[2]/input");

        // verify if the result is 5
        String result = selenium.getText("//*[@id='content']/p[2]/span/font/b");
        System.out.println(result);


        if (result == "5") {
            System.out.println("Pass");
        } else {
            System.out.println("Fail");
        }
    }
}

问题是在执行上述代码时,getText() 行发生异常。我从 Google Chrome 的开发者工具中复制了那个 XPath。即使我手动检查过一次,也会显示相同的 XPath。从今天早上开始,我一直试图找到解决方案。如何让 Selenium 找到元素?

PS:在结果变量中,我必须在计算后捕获结果。例如 10 % 50 = 5。这 5 我需要捕获。

【问题讨论】:

    标签: java selenium xpath


    【解决方案1】:

    您需要等待“结果”被填充。

    这是更新后的代码 sn-p,它应该适合你:

        //add this line
        if (!selenium.isElementPresent("//*[@id='content']/p[2]/span/font/b")){
        Thread.sleep(2000);
        }
        // verify if the result is 5
        String result = selenium.getText("//*[@id='content']/p[2]/span/font/b");
        System.out.println(result);
    
        //update this line
        if (result.trim().equals("5"))
        {
            System.out.println("Pass");
        }else
        {
            System.out.println("Fail");
        }
    

    你需要使用.equals方法来比较两个字符串值。

    注意 - 更好的方法是将 Thread.sleep 替换为动态等待方法,例如 waitForPageToLoad、waitForElementPresent(自定义方法)等...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-04
      • 1970-01-01
      • 2021-08-17
      • 2020-08-17
      • 1970-01-01
      相关资源
      最近更新 更多