Getting error while running selenium code - selenium

I am getting below error while running selenium code while everything is right in code. Please help
Exception in thread "main" com.thoughtworks.selenium.SeleniumException: ERROR: Element .//*[#id='content']/p[2] not found
at com.thoughtworks.selenium.HttpCommandProcessor.throwAssertionFailureExceptionOrError(HttpCommandProcessor.java:109)
at com.thoughtworks.selenium.HttpCommandProcessor.doCommand(HttpCommandProcessor.java:103)
at com.thoughtworks.selenium.HttpCommandProcessor.getString(HttpCommandProcessor.java:272)
at com.thoughtworks.selenium.DefaultSelenium.getText(DefaultSelenium.java:471)
at selrcdemo.RCDemo.main(RCDemo.java:35)
package selrcdemo;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;
public class RCDemo {
public static void main(String[] args) throws InterruptedException
{
Selenium selenium = new DefaultSelenium("localhost", 4444 , "firefox", "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(2500); // Wait for page load
// Click on Link Percent Calculator
selenium.click("xpath=.//*[#id='menu']/div[4]/div[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");
Thread.sleep(4000);
// verify if the result is 5
String result = selenium.getText(".//*[#id='content']/p[2]");
if (result == "5")
{
System.out.println("Pass");
}else
{
System.out.println("Fail");
}
}
}

If you open this site, you'll find that the output is not getting stored in the third text box, rather it is getting displayed above, just under where "Result" is written.
You'll have to make some changes in the code(the xpath for click button and that for the third text box, i.e. from where the value is getting picked). The following codes works perfectly:
package seleniumrcdemo;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;
#SuppressWarnings("deprecation")
public class rcdemo {
public static void main(String[] args) throws InterruptedException {
// Instatiate the RC Server
Selenium selenium = new DefaultSelenium("localhost", 4444 , "firefox", "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(2500); // Wait for page load
// Click on Link Percent Calculator
selenium.click("xpath=.//*[#id='menu']/div[4]/div[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[1]/tbody/tr[2]/td/input[2]");
// verify if the result is 5
Thread.sleep(4000);
String result = selenium.getText("xpath=.//*[#id='content']/p[2]/font/b");
//String result = selenium.getValue("xpath=.//*[#id='cpar3']");
System.out.println("result"+result);
if (result.equals("5")/*== "5"*/){
System.out.println("Pass");
}
else{
System.out.println("Fail");
}
}
}

Pretty sure you need to add xpath= inside your quotes. Or do:
String result = selenium.findElement(By.xpath('path')).getText();
Your answer (result) doesn't exist in the second p. After closer inspect the xpath is:
/html/body/table[2]/tbody/tr/td[1]/div[1]/p[2]/span

The statement
String result = selenium.getText(".//*[#id='content']/p[2]");
missing the "xpath=".
The correct statement
String result = selenium.getText("xpath=.//*[#id='content']/p[2]");
But this will return the result "10% of 50 = 5", which of course != "5". The exact xpath is for the element "5" is "xpath=.//*[#id='content']/p[2]/span/font/b". So the statement should be
String result = selenium.getText("xpath=.//*[#id='content']/p[2]/span/font/b");
You'll still get "Fail" in comparing the String literals. Suggest to use equals() or compareTo() method when comparing strings:
if (result.equals("5"))
{
System.out.println("Pass");
}else
{
System.out.println("Fail");
}
Hope this helps.

Thread.sleep(2000);
// verify if the result is 5
String result = selenium.getText("xpath=.//*[#id='content']/p[2]/span/font/b");
if (result.equals("5")){
System.out.println("Pass");
}
else{
System.out.println("Fail");
}

correct me if I am wrong
the % calculation module in calculator web application is failed to pass test case, may be the application code requires a bug fix , the result is not displaying on the rhs(cpar3) side
xpath=.//*[#id='cpar3']==>RHS xpath
here is the selenium code which works fine for me if i manually enter the result value to 5
package selRcDemo;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;
public class RcDemo {
/**
* #param args
*/
public static void main(String[] args) throws InterruptedException {
// Instatiate the RC Server
Selenium selenium = new DefaultSelenium("localhost", 4444, "firefox",
"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(2500); // Wait for page load
// Click on Link Percent Calculator
selenium.click("xpath=.//*[#id='menu']/div[4]/div[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[1]/tbody/tr[2]/td/input[2]");
Thread.sleep(2500);
// verify if the result is 5
String result = selenium.getText("xpath=.//*[#id='cpar3']");
// result="5";
System.out.println(result);
// result is not equal to 5 due to bug in application code its returning
// "" (no value)
if (result.equals("5")) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
}
}

Related

i want to automate onpresskey event in selenium how can i automate

i have one form and i want to test invalid credential(for ex.test #) and in my code i passed text when i run the code it take test not # )
.
#Then("user enter invalid credentials")
public void user_enter_invalid_credentials() throws InterruptedException {
WebElement text=driver.findElement(By.xpath("//*[#id=\"rule-name\"]"));
//enter text
text.sendKeys("Testing# ");
// get value attribute with getAttribute()
String val = text.getAttribute("value");
System.out.println("Entered text is: " + val);
Thread.sleep(3000);
}
how can i validate onpressevent using selenium

Selenium - WebElement.Click(), page refreshes but not loading

Using pagefactory and selenium 3 with Java, I have created a simple script to login and logout. I have used the below for explicit wait:
public void verifyElementisEnabled( WebElement wElement,String sFieldName){
printCurrentDate();
try{
wait.until(ExpectedConditions.elementToBeClickable(wElement));
wait.until(ExpectedConditions.visibilityOf(wElement));
**//Thread.Sleep("1000") - Script works if this line is uncommented**
if (wElement.isEnabled()==true)
System.out.println(sFieldName + " is enabled");
printCurrentDate();
}catch (Exception e){
printCurrentDate();
System.out.println(sFieldName + " is NOT enabled");
Assert.fail(sFieldName + " Field not found", e);
}
}
The issue I'm facing is, for the Logout, after the webelement click, the page refreshes briefly for a second but the appropriate Login page is not displayed, instead it stays in the same page. I don't see any exception for weblement before click. Below is the code snippet.
However all of this works if I use "Thread.Sleep(1000)" in the above "VerifyElementisEnabled method (anything less than 1000 is not working)
#Test
public void Test1(){
LoginPage objLogin = new LoginPage(driver);
objLogin.setUserName();
objLogin.setPwd();
HomePage objHome = objLogin.clickLoginButton();
objHome.confirmHomePage();
objLogin = objHome.SignOut();
objLogin.verifyLoginPage();
}
public LoginPage SignOut(){
commonLib.click_webelement(SignOut,"Sign Out");
commonLib.waitForPagetoLoadJS_Ajax();
return new LoginPage(driver);
}
Wait for JS and Ajax method, just verifies if the document.ready status is complete.
I'm out of ideas here, any suggestions or help will be much appreciated.
Thanks!
Updated:
public void confirmHomePage(){
commonLib.verifyElementisEnabled(titleText, "User Search");
}
Final update:
Looks like the parent class Test1 given above had issues. After performing the tests, the webdriver was returning to the previous page "Login". Here I was returning the "Login Page" class. This was obstructing with the page navigation. I updated the Test1 as below:
public void afcDealerTest1(){
LoginPage objLogin = new LoginPage(driver);
objLogin.enterLoginCredentials();
HomePage objHome = objLogin.clickLoginButton();
objHome.confirmHomePage();
objHome.SignOut(); //<-- Refer to this line
objLogin.verifyLoginPage();
}
Also removed all the thread.sleep in all the methods, except for the JS Ready status as complete with a 200ms sleep. It seems to be working fine.
Thanks everyone for all the help.
It is sync issue. It seems element gets enable after some time which bypassing your explicit conditions. You should wait till element is enable.
Fixed it by this modification below:
Before:
#Test
public void Test1(){
LoginPage objLogin = new LoginPage(driver);
objLogin.setUserName();
objLogin.setPwd();
HomePage objHome = objLogin.clickLoginButton();
objHome.confirmHomePage();
objLogin = objHome.SignOut();
objLogin.verifyLoginPage();
}
Fix:
#Test
public void Test1(){
LoginPage objLogin = new LoginPage(driver);
objLogin.setUserName();
objLogin.setPwd();
HomePage objHome = objLogin.clickLoginButton();
objHome.confirmHomePage();
objHome.SignOut();
objLogin.verifyLoginPage();
}

Selenium WebDriver based framework using POM with java

I am trying to write code to validate a webpage (Test Form with 3 required fields firstname, lastname, phone and 2 buttons submit and clear form) using POM with Selenium WebDriver with Java.
This is the code which I have written so far. I want to confirm whether I am going in the right way.
public class TestForm {
WebDriver driver;
By firstName=By.id("fname");
By lastName=By.id("lname");
By phoneno=By.id("phone");
By submit=By.id("submit");
By clearForm=By.xpath("//tagname[#type='button']");
public TestForm(WebDriver driver)
{
this.driver=driver;
}
public void typeFirstName(String fname)
{
driver.findElement(firstName).sendKeys(fname);
}
public void typeLastName(String lname)
{
driver.findElement(lastName).sendKeys(lname);
}
public void typePhone(String phone)
{
driver.findElement(phoneno).sendKeys(phone);
}
public void clickSubmit()
{
driver.findElement(submit).click();
}
public void clickClearForm()
{
driver.findElement(clearForm).click();
}
}
public class VerifyTestForm {
#Test
public void verifyValidTestForm()
{
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.get("url of the application");
TestForm form=new TestForm(driver);
form.typeFirstName("John");
form.typeLastName("Adams");
form.typePhone("1234567890");
form.clickSubmit();
form.clickClearForm();
driver.quit();
}
}
Most code look good, except following items:
1) By clearForm=By.xpath("//tagname[#type='button']");
tagname should be a correct tag, like button or 'input'
2) After click Submit, the page still stay the form page, If so call clickClearForm should work.
form.clickSubmit();
form.clickClearForm();
3) There is no any check point/validation in your code, all are operateion on page.
// Assume an new page will open after click Submit button
// You need to check the new page opened by check page title if it'll change
// or check an element belongs to the new page is displayed
Assert(driver.getTitle()).toEqual('xxx')
Assert(driver.findElement(xxx).isDisplay()).toBe(true)
// above code may not exact correct, dependent on you choose Junit, TestNG
// or third-party Assert library.
// After click `Clear/Reset` button, you should check all fields reset to default value
Assert(form.readFirstName()).toEqual("")
4) For test class name VerifyTestForm, it's better start or end with Test, like Testxxx or xxxTest
As your code is correct but it is not the way to implementing Page object Model.
You have to use concept of DataProvider to implement framework.
Make a excel sheet and extract the data by using DataProvider.
Make a new class file from where you can read your excel data.
Make a function which return 2d data of the file.
So By using this, The way to implement the framework.
Page object Model generally says that we should have to make the separate page of each module which we are using and return the reference of the last page.

Not able to identify element on the screen- how to use tab

Screenshot of the element I want to click:
I automating my website(new to automation). once i login i get to another page where selenium web driver is not able to find any of the elements(I tried all possibilities even sso related).
Only solution i could find was using tabs and enter.
So when i enter that page i need to click 9 time "TAB" key from the keyboard and then enter so that my login is verified. since i don't have any element using which i can perform the tab and enter actions. is there a way where once i get to that page the web driver starts pressing "TAB" key 9 times and then "Enter" on 10 time.
Please help I have been working on this over a week now and not getting
anywhere.
optimist_creeper-main class:
package Modules;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
import Modules.HomePage;
public class MainClass {
String appUrl = "als-stg-1.mtvn.ad.viacom.com/webqa/";
#Test public void MainTest() {
System.setProperty("webdriver.gecko.driver", "C:\\Shayni Coding\\Automation\\Gecko\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get(appUrl);
HomePage home = new HomePage();
home.HomePageTest(driver);
}
}
Home Page class:
public class HomePage {
#BeforeClass public void beforeClass() {
System.out.println("before class");
}
public void HomePageTest(WebDriver driver) {
driver.manage().window().maximize();
WebElement email = driver.findElement(By.id("cred_userid_inputtext"));
email.sendKeys("shayni#outlook.com");
WebElement pass = driiver.findElement(By.id("cred_password_inputtext"));
pass.sendKeys(Keys.ENTER);
pass.click();
String expectedTitle = "VMS Web";
String actualTitle = driver.getTitle();
Assert.assertEquals(expectedTitle,actualTitle);
}
}
Thanks.
Just get a random object like the body tag and use that to send your key presses.
e.g.
WebElement dummyElement = driver.findElement(By.xpath("/html/body"));
for (int i = 0; i < 9; ++i) {
dummyElement.sendKeys(keys.TAB);
}
dummyElement.sendKeys(keys.ENTER);
The above code finds the body take and sets it as an element. It then presses the tab key 9 times and then presses the enter key. Which is what you asked for. Hope that helps.

Selenium C# Webdriver How to detect if element is visible

Is there a way in the latest version of Selenium DotNet Webdriver (2.22.0) to check to see if an element is visible before clicking/interacting with it?
The only way I've found is to try to handle the ElementNotVisible exception that occurs when you try to send keys, or click on it. Unfortunately this only occurs after an attempt to interact with the element has been made. I'm using a recursive function to find elements with a certain value, and some of these elements are only visible in certain scenarios (but their html is still there no matter what, so they can be found).
It's my understanding that the RenderedWebElement class is deprecated as well other variants. So no casting to that.
Thanks.
For Java there is isDisplayed() on the RemoteWebElement - as well is isEnabled()
In C#, there is a Displayed & Enabled property.
Both must be true for an element to be on the page and visible to a user.
In the case of "html is still there no matter what, so they can be found", simply check BOTH isDisplayed (Java) / Displayed (C#) AND isEnabled (Java) / Enabled (C#).
Example, in C#:
public void Test()
{
IWebDriver driver = new FirefoxDriver();
IWebElement element = null;
if (TryFindElement(By.CssSelector("div.logintextbox"), out element)
{
bool visible = IsElementVisible(element);
if (visible)
{
// do something
}
}
}
public bool TryFindElement(By by, out IWebElement element)
{
try
{
element = driver.FindElement(by);
}
catch (NoSuchElementException ex)
{
return false;
}
return true;
}
public bool IsElementVisible(IWebElement element)
{
return element.Displayed && element.Enabled;
}
It seems the current answer to this question is outdated: With WebDriver 3.13 both the Displayed and Enabled properties will return true as long as the element exists on the page, even if it is outside of the viewport. The following C# code works for WebDriver 3.13 (from this StackOverflow answer):
{
return (bool)((IJavaScriptExecutor)Driver).ExecuteScript(#"
var element = arguments[0];
var boundingBox = element.getBoundingClientRect();
var cx = boundingBox.left + boundingBox.width/2, cy = boundingBox.top + boundingBox.height/2;
return !!document.elementFromPoint(cx, cy);
", element);
}
There is a simple way to do that, follow below:
public bool ElementDisplayed(By locator)
{
new WebDriverWait(driver, TimeSpan.FromSeconds(timeOut)).Until(condition: ExpectedConditions.PresenceOfAllElementsLocatedBy(locator));
return driver.FindElement(locator).Displayed ;
}
You can use the following:
WebDriver web = new FirefoxDriver(;
String visibility = web.findElement(By.xpath("//your xpath")).getCssValue("display");