Issue
I am completely new to Selenium and XPath. Today is the first time I am trying to execute a simple script using Selenium RC. Please find the code below.
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 the 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");
}
}
}
The issue is when executing the above code, an exception is happening at the getText()
line. I copied that XPath from the developer tools of Google Chrome. Even when I checked manually once, the same XPath expression is showing. I have tried to find the solution for this from today morning. How can I get Selenium to find the element?
PS: In the result variable I have to capture the result after a calculation. For example, 10 % 50 = 5. This 5 I need to capture.
Solution
You need to wait for "Result" to get populated.
Here is the updated code snippet. It should work for you:
// 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");
}
And you need to use the .equals
method to compare the two string values.
Note - A better approach is to replace Thread.sleep with dynamic wait methods, like waitForPageToLoad, waitForElementPresent (custom methods), etc.
Answered By - Surya
Answer Checked By - Candace Johnson (JavaFixing Volunteer)