How to check if element is visible or not - java

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());
}
}

Related

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 get INPUT field data in eclipse?

I am tried to using following syntaxes but, I didn't get result.
package demo_package;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Class {
public WebDriver driver= new FirefoxDriver();
#BeforeTest
public void beforetest() {
driver.get("URL");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
}
#Test
public void Login() {
driver.findElement(By.id("username")).sendKeys("username");
driver.findElement(By.id("password")).sendKeys("password");
driver.findElement(By.id("login")).click();
}
#Test
public void Gettext() {
driver.findElement(By.id("psge_click")).click();
WebElement msg=driver.findElement(By.id("input_id"));
String expectedText=("sample text");
String text=msg.getText();
System.out.println(text);
Assert.assertEquals(text,expectedText);
}
I am using this code for ERROR Message, getting result, but input data not getting "empty" is displayed
Try as below to get the data from input field :-
WebElement msg=driver.findElement(By.id("input_id"));
String text = msg.getAttribute("value");
Hope it will help you....:)

WaitForElement in Selenium WebDriver?

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.

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();

Need to supress sops for second duplicate String onwards.

import java.util.HashSet;
import java.util.concurrent.TimeUnit;
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.support.ui.Select;
public class Demo27 {
public static void main(String[] args)
{
WebDriver driver=new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("file:///C:/Users/Administrator/Desktop/listDropdown.html");
WebElement listElement=driver.findElement(By.id("countrySelect"));
Select select=new Select(listElement);
List<WebElement> elements=select.getOptions();
int count=elements.size();
HashSet<String> set=new HashSet<String>();
for(int i=0;i<count;i++)
{
WebElement singleElement=elements.get(i);
String text=singleElement.getText();
if(!set.add(text))
{
System.out.println(text+"is duplicated");
}
}
driver.close();
}
}
You can write a logic this way. I have created an ArrayList to capture the duplicate values. I will have it for reference if the incoming text is found in the duplicate list. If it is not present, then i will print it. Otherwise, i will just ignore. This way you can suppress the second duplicate text to be printed
boolean isSet = false;
List<String> duplicates = new ArrayList<String>();
if((isSet = set.add(text))){
//this will get printed for only unique values added
System.out.println(text+"is unique");
}
else{
if(!duplicates.contains(text)){
duplicates.add(text);
System.out.println(text+"is first duplicate");
}
}

Categories

Resources