WaitForElement in Selenium WebDriver? - java

Currently, I am using Thread.sleep to make the scripts to wait for certain element to be loaded. Execution takes long time.. Instead this, i need something waitforElement once it is displayed i need to continue my execution rather this Thread.sleep..
Can someone tell me that the below logic looks ok??
package com.test.utility;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class WaitForElement extends globalVariables {
public static void waitfor(String locator) {
try {
WebDriverWait Test_Wait = new WebDriverWait(driver, 60);
WebElement locatorvalue = common.getObject(locator);
Boolean click = Test_Wait.until(ExpectedConditions
.elementToBeSelected(locatorvalue));
} catch (Throwable e) {
System.err.println("The element is not found");
}
}
}

I have used this similar code in my project and it works for me.

Related

Not able to select the first row after applying a filter in a grid while using Selenium with java [tricky situation]

I am getting this strange scenario.
Been searching for a long time without success, what is going on?
Let me explain you:
I am trying to create an automation in a webpage, i have to enter a
specific value in a dinamic table and after performing a "ENTER" event
it is necessary to select the first row shown:
After running my code i got this but the row shown is not been selected, it is stuck:
This is my code:
package first;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Script_codes {
public static void main(String[] args){
System.setProperty("webdriver.chrome.driver","C:\\Users\\Steve\\Desktop\\Me\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://stage.nbm2.test/backend");
driver.findElement(By.id("username")).sendKeys("test");
driver.findElement(By.id("login")).sendKeys("test");
driver.findElement(By.xpath("//*[#id=\"login-form\"]/fieldset/div[3]/div[2]/button")).click();
driver.findElement(By.xpath("//*[#id=\"menu-magento-backend-stores\"]/a")).click();
driver.findElement(By.xpath("//*[#id=\"menu-magento-backend-stores\"]/div/ul/li[2]/ul/li[2]/div/ul/li[3]/a")).click();
driver.findElement(By.xpath("//*[#id=\"attributeGrid_filter_frontend_label\"]")).sendKeys("linea");
driver.findElement(By.xpath("//*[#id=\"attributeGrid_filter_frontend_label\"]")).sendKeys(Keys.ENTER);
driver.findElement(By.className("col-label col-frontend_label")).click();
}
}
I have tried many different ways but it seems not to be working, what can i do?
Expected output:
I would first try the following to see if timing is the issue:
package first;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Script_codes {
public static void main(String[] args){
System.setProperty("webdriver.chrome.driver","C:\\Users\\Steve\\Desktop\\Me\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://stage.nbm2.test/backend");
Thread.sleep(1000);
driver.findElement(By.id("username")).sendKeys("test");
Thread.sleep(1000);
driver.findElement(By.id("login")).sendKeys("test");
Thread.sleep(1000);
driver.findElement(By.xpath("//*[#id=\"login-form\"]/fieldset/div[3]/div[2]/button")).click();
Thread.sleep(1000);
driver.findElement(By.xpath("//*[#id=\"menu-magento-backend-stores\"]/a")).click();
Thread.sleep(1000);
driver.findElement(By.xpath("//*[#id=\"menu-magento-backend-stores\"]/div/ul/li[2]/ul/li[2]/div/ul/li[3]/a")).click();
Thread.sleep(1000);
driver.findElement(By.xpath("//*[#id=\"attributeGrid_filter_frontend_label\"]")).sendKeys("linea");
Thread.sleep(1000);
driver.findElement(By.xpath("//*[#id=\"attributeGrid_filter_frontend_label\"]")).sendKeys(Keys.ENTER);
Thread.sleep(1000);
driver.findElement(By.className("col-label col-frontend_label")).click();
}
}
If this works, I expect it will be fairly simple to identify which step(s) needs extra time. For this wait, I suggest you implement the WebDriverWait class for better stability and execution time.
I was able to solved my problem by using:
driver.findElement(By.xpath("//*[#id=\"attributeGrid_table\"]/tbody/tr/td[1]")).click();
instead of:
driver.findElement(By.className("col-label col-frontend_label")).click();

how to pass more than one web elements to page using phantomjs

I am trying to use phantomjs for testing, I have one login page with obvious two parameters username and password. If i try same code with google url where i have to pass only one element with and say element.submit(); but in my login page i want to pass two elements how to achieve the same ?
here is my code -
import java.io.File;
import java.io.IOException;
import org.apache.maven.shared.utils.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.Test;
public class PhantomExample {
public PhantomExample() {
System.out.println("this is constructor");
}
#Test
public void verify() {
File src = new File("C:\\Users\\Admin\\Downloads\\Compressed\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");
DesiredCapabilities phantomjsCap = new DesiredCapabilities();
phantomjsCap.setJavascriptEnabled(true);
phantomjsCap.setCapability("phantomjs.binary.path", src.getAbsolutePath());
System.out.println("inside the verify method");
System.setProperty("phantomjs.binary.path", src.getAbsolutePath());
WebDriver driver = new PhantomJSDriver(phantomjsCap);
driver.get("http://localhost:8080/MyApp/Login");
System.out.println(driver.getPageSource());
WebElement el =driver.findElement(By.name("username"));
WebElement elp =driver.findElement(By.name("password"));
el.sendKeys("username");
elp.sendKeys("0");
el.submit();
elp.submit();
System.out.println(driver.getTitle());
System.out.println(driver.getCurrentUrl());
System.out.println(driver.getPageSource());
File Ss=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(Ss, new File("d:/sample.jpg"));
}
catch (IOException e) {
System.out.println(e.getMessage());
}
driver.quit();
}
}
Here i created two separate elements and expecting to get the response, but when i run it in debugger mode it is not executing after line el.submit();
I am quite sure that i am doing this wrong way, but can someone tell me what is the right approach to this and explain how to get response object which server would send after log in ?
Calling the submit() method on an input field submits the whole form (with all input values), so the following line can be deleted:
elp.submit();
If the form has a submit button, then after executing el.submit() login will be done.

How to close pop up in selenium webdriver?

I am trying to close pop up using selenium web driver with java. I have tried different ways, but unable to succeed. Please help me.
package Demo;
import java.util.Set;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class YahooTest {
public static void main(String[] args) throws InterruptedException {
FirefoxDriver obj = new FirefoxDriver();
String url = "https://www.planyourjourney.com/";
obj.get(url);
obj.manage().window().maximize();
obj.findElement(By.xpath("html/body/div[12]/div/div/div[9]")).click();
obj.findElementByClassName("dyna-link-new-registration").click();
obj.findElement(By.linkText("B2B Login")).click();
Thread.sleep(4000);
obj.findElement(By.id("userid")).clear();
obj.findElement(By.id("userid")).sendKeys("1592jet#gmail.com");
obj.findElement(By.id("ulPassword")).clear();
obj.findElement(By.id("ulPassword")).sendKeys("spyj01");
obj.findElement(By.name("Next")).click();
Thread.sleep(2000);
obj.findElement(By.id("affilitetrainadvpage"));
Alert alert = obj.switchTo().alert();
alert.dismiss();
}
}
I have seen the source code of the web page and could not find any alert in it.
The pop-up is actually written inside a div tag.
Hence, remove the codes related to alert and use below code which uses xpath.
obj.findElement(By.xpath("//*[#id='affilitetrainadvpage']/span/a/img")).click();

How to check if element is visible or not

Need your help wanted to check if particular element is visible or not.
in the below code I have passed wrong ID so that system will throw NoSuchElementException in the case of correct element it is giving correct answer. But in the case of wrong element it is throwing exception instead of handling it.
Please help in this -
package com;
import java.util.NoSuchElementException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
public class Windowgoogle {
static WebDriver driver;
static String baseUrl="http:/www.google.co.in";
#Test
public void openBrowser()
{
driver=new FirefoxDriver();
driver.get(baseUrl);
System.out.println(existsElement("qo"));//Adding Invalid ID
}
private boolean existsElement(String id)
{
boolean chk = false;
try {
chk=driver.findElement(By.name(id)).isDisplayed();
return chk;
} catch (NoSuchElementException e)
{
return false;//Control should go to catch but exception is not getting handled properly.
}
}
}
You have imported wrong NoSuchElementException. You should have imported
org.openqa.selenium.NoSuchElementException
instead of java.util.NoSuchElementException
Alternatively, you are able to use driver.findElements as a way to determine if the element is present on the page without using the NoSuchElementException.
For this you would use:
private boolean existsElement(String id) {
return !driver.findElements(By.name(id)).isEmpty();
}
When the method findElements cannot find any elements that match the specified locator, it returns an empty list. It is a very common alternative to catching the NoSuchElementException.
While catching NoSuchElementException works, it's not an elegant solution. Imagine if you have to have this logic in multiple places. The code will be bloated and hard to maintain. You can use helper methods from ExpectedConditions class. This is how you would use it,
WebDriverWait wait = new WebDriverWait(driver,30);
boolean isNotVisible = wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id("foo")));
if(isNotVisible) {
// do stuff
}
import java.util.NoSuchElementException;
import org.openqa.selenium.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
public class dropdown {
private static WebDriver driver = new FirefoxDriver() ;
String Path ="C:\\Users\\VGupta\\Desktop\\testcases\\auto.xlsx";
#Test
public void test() throws Exception
{
driver.get("http://www.test.com/");
//Dimension size = ('900','500');
driver.manage().window().setSize(new Dimension(1000,1000));
try{
driver.findElement(By.id("foo")).click();
} catch(NoSuchElementException e)
{
System.out.println(e.getStackTrace());
}
}

Selenium "Cannot locate element used to submit form"

I am using the Selenium Library to try and log in to www.marketwatch.com for me. It can find all the elements, but upon calling the .submit() method, I get a "Cannot locate element used to submit form" error. When using button.click(), nothing happens at all. Thanks
package com.logansnow.marketwatch;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.Keys;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Main {
public static void main(String[] args){
java.util.logging.Logger.getLogger("com.gargoylesoftware.htmlunit").setLevel(java.util.logging.Level.OFF);
java.util.logging.Logger.getLogger("org.apache.http").setLevel(java.util.logging.Level.OFF);
WebDriver driver = new HtmlUnitDriver();
driver.get("https://id.marketwatch.com/access/50eb2d087826a77e5d000001/latest/login_standalone.html?url=http%3A%2F%2Fwww.marketwatch.com%2Fuser%2Flogin%2Fstatus");
WebElement email = driver.findElement(By.name("username"));
WebElement loginPass = driver.findElement(By.name("password"));
WebElement button = driver.findElement(By.id("submitButton"));
email.sendKeys("***********#gmail.com");
loginPass.sendKeys("******************");
//loginPass.submit();
driver.findElement(By.className("login_submit")).click();
email.submit();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(driver.getTitle());
}
}
Problem seems to be stemming from email.submit(); statement. You need one of the two statements really to submit the form.
package com.logansnow.marketwatch;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.Keys;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Main {
public static void main(String[] args){
java.util.logging.Logger.getLogger("com.gargoylesoftware.htmlunit").setLevel(java.util.logging.Level.OFF);
java.util.logging.Logger.getLogger("org.apache.http").setLevel(java.util.logging.Level.OFF);
WebDriver driver = new HtmlUnitDriver();
driver.get("https://id.marketwatch.com/access/50eb2d087826a77e5d000001/latest/login_standalone.html?url=http%3A%2F%2Fwww.marketwatch.com%2Fuser%2Flogin%2Fstatus");
WebElement email = driver.findElement(By.name("username"));
WebElement loginPass = driver.findElement(By.name("password"));
WebElement button = driver.findElement(By.id("submitButton"));
email.sendKeys("***********#gmail.com");
loginPass.sendKeys("******************");
//loginPass.submit();
// Click on the submit button to submit the form.
driver.findElement(By.className("login_submit")).click();
// Can also use this since you already have WebElement referencing the submit button.
// button.click();
// Or invoke submit on the button element
// button.submit();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(driver.getTitle());
}
}
Do submit using below . Just replace your submit code with below :
driver.findElement(By.id("submitButton")).click();
If your webpage contains javascript, HTMLUnitDriver doesn't enable javascript by default.
Make sure you are enabling javascript using the constructor parameter.
WebDriver driver = new HtmlUnitDriver();

Categories

Resources