2014-11-16 114 views
0

我对Selenium和XPath完全陌生。今天是我第一次尝试使用Selenium RC执行一个简单的脚本。请找到下面的代码。由于XPATH不正确而导致Selenium“元素未找到”

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我需要捕捉。

回答

1

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

以下是更新的代码段,它应该为你工作:

//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方法来比较两个字符串值。

注 - 更好的方法是用动态wait方法一样,waitForPageToLoad,waitForElementPresent(自定义方法)等取代了Thread.sleep ...

+0

感谢surya..It工作的罚款。 – user3196470

相关问题