Selenium: Presence of a particular WebElement on all pages in the website - selenium

We have a search widget at the top of the page in all the pages. I want to check, if that widget is visible on all the pages of the website. Is there any smarter way, rather than going to all the pages and checking it?

Answering straight, when you want to check if an widget is visible or not we should have used a method isVisible(). But isVisible() was available in Selenium RC which is deprecated in current WebDriver implementations. Instead referring to the documentation we can use either of these methods isDisplayed(), isEnabled() or isSelected().
So when you speak about search widget at the top of the page in all the pages I feel isDisplayed() method fits into your requirement. For example let us take an example of the Search field on stackoverflow.com Homepage which is available on all the pages. Now we want to check, if that widget is visible on all the pages of the website or not. A sample code block can be as follows:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class A_Firefox
{
public static void main(String[] args)
{
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://stackoverflow.com");
System.out.println("Application opened");
System.out.println("Page Title is : "+driver.getTitle());
WebElement my_element = driver.findElement(By.xpath("//input[#name='q']"));
if(my_element.isDisplayed())
{
System.out.println("Element is displayed");
}
else
{
System.out.println("Element is not displayed");
}
driver.quit();
}
}
The output on my console is:
Application opened
Page Title is : Stack Overflow - Where Developers Learn, Share, & Build Careers
Element is displayed
Enhancement:
As an enhancement you can create a function as presenceOfSearchBox(WebElement ele) and pass the WebElement as an argument from every page you visit to validate if the widget is displayed or not as follows:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class A_Firefox
{
public static void main(String[] args)
{
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://stackoverflow.com");
System.out.println("Application opened");
System.out.println("Page Title is : "+driver.getTitle());
WebElement my_element = driver.findElement(By.xpath("//input[#name='q']"));
presenceOfSearchBox(my_element);
driver.quit();
}
public static void presenceOfSearchBox(WebElement ele)
{
if(ele.isDisplayed())
{
System.out.println("Element is displayed");
}
else
{
System.out.println("Element is not displayed");
}
}
}

Related

How to select second one in trending list of google webpage?

package jdjjddk;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Htegsbn {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\hp\\Downloads\\Compressed\\Chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com/");
driver.findElement(By.xpath("//input[#title='Search']")).click();
driver.findElement(By.xpath("//div[normalize-space()='Trending searches'][2]")).click();
}
}
This is the code I wrote, while executing it stops at displaying the trending list but not clicking the second one.
In Selenium you have FindElements:
List<Element> elements = driver.findElements
(By.xpath("//div[normalize-space()='Trending searches']"));
elements[2].click();

WebElement Click() showing NullPointerException in Selenium

I was trying Selenium automation testing in https://www.yatra.com/etw-desktop/ . My objective was to click an Image Button named 'Asia' which will redirect to another page (Images attached). I copied the full XPath and tried but I am getting a NullPointerException. Please give some suggestions since I didn't find anything wrong with my code.
package com.stackroute.SeleniumProject;
import java.util.concurrent.TimeUnit;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.FindBy;
/**
* JUnit project.
*/
public class Yatra {
public static WebDriver driver = null;
#FindBy(xpath = "/html/body/my-app//app-drawer-layout/app-header-layout/iron-pages/my-home//div/div/div/div/paper-material[2]/div[1]/div/a[2]/div[4]")
WebElement Asia;
#BeforeClass
public static void setup() {
String chromePath = System.getProperty("user.dir") + "/lib/chromedriver.exe";// directory of chrome driver
System.setProperty("webdriver.chrome.driver", chromePath);
driver = new ChromeDriver();
}
#AfterClass
public static void close() throws InterruptedException {
driver.close();
}
#Test
public void test1() throws InterruptedException {
driver.manage().window().maximize();
driver.get("https://www.yatra.com/etw-desktop/");
driver.manage().timeouts().implicitlyWait(4000, TimeUnit.MILLISECONDS);
Thread.sleep(5000);
// the error is in the below line Asia.click()
Asia.click();
driver.manage().timeouts().implicitlyWait(5000, TimeUnit.MILLISECONDS);
Thread.sleep(2000);
Assert.assertEquals("page not found", "https://www.yatra.com/etw-desktop/city-list", driver.getCurrentUrl());
}
}
Image showing the element to be clicked
Image of web page after click operation
You are using PageFactory(from page object model), so you will need to init() the webelements.
For this you will need to import
org.openqa.selenium.support.PageFactory;
An before starting the test, you will need to initialise the elements:
PageFactory.initElements(driver, this) // where you pass the driver and this class to know which webelements to start.
You can take a look here to understand the approach and another POM framework easier to understand TUTORIAL

Locating iFrames and controls within them using Selenium WebDriver

I'm trying to automate www.snapdeal.com using Selenium Webdriver. I'm not able to click a web element inside an iframe as I get Element not visible exception.
Below is the code snippet
package com.snapdeal.framework.rough;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class Lab {
public static WebDriver browser;
public static WebElement currentElement;
public static Actions actions;
public static void main(String[] args) {
//System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"//src//main//resources//chromedriver.exe");
browser = new FirefoxDriver();
browser.get("http://www.snapdeal.com");
browser.manage().window().maximize();
browser.findElement(By.xpath("//*[#id='pincodeSalienceComponent']/div[2]/i")).click();
actions = new Actions(browser);
actions.moveToElement(browser.findElement(By.xpath("//*[#id='accountHeader']/div[1]"))).perform();
actions.moveToElement(browser.findElement(By.xpath("//*[#id='accountHeader']/div[2]/div[2]/div[1]/p/span[2]"))).click().build().perform();
//By executing a java script
JavascriptExecutor exe = (JavascriptExecutor) browser;
Integer numberOfFrames = Integer.parseInt(exe.executeScript("return window.length").toString());
System.out.println("Number of iframes on the page are " + numberOfFrames);
//By finding all the web elements using iframe tag
List<WebElement> iframeElements = browser.findElements(By.tagName("iframe"));
System.out.println(iframeElements.get(0));
System.out.println("The total number of iframes are " + iframeElements.size());
try{
browser.switchTo().frame(1);
}catch(Exception e){
System.out.println(e.getMessage());
}
try{
browser.findElement(By.xpath("//*[#id='login-register-modal']/div[2]/div[2]/div[2]/div")).click();
}catch(Exception e){
System.out.println(e.getMessage());
}
browser.close();
}
}
Could you please guide me on how to get this resolved?
You need to switch to iframe:
// click Mobile number and email button first an then
driver.switchTo().frame("loginIframe");
// after registration is done switch back to top frame:
driver.switchTo().defaultContent();

Auto suggestion list Element's are displayed twice in the result set in Console,what ll be the code to click on list element on the basis of text

Following is the code to get the list elements name and click on the desired list element: below is the attachment of result : Console displaying list items twice : what could be the other ways to pick the complex Auto suggestion list
elements of a web application.
package Pages;
import org.testng.annotations.Test;
import java.util.List;
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.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class Login {
WebDriver driver;
String baseUrl="http://www.flipkart.com/";
#BeforeTest
public void flipkartSetup()
{
driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
}
#Test(priority=0)
public void flipkartLoginpage()
{
//open the webpage :s
driver.get(baseUrl);
//click on Login
driver.findElement(By.xpath(".//div[#id='container']//header/div[2]/div/div[1]/u l/li[8]/a")).click();
//wait for 30 second
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
//Enter mobile into the text box
driver.findElement(By.xpath("//div[#class='login-input-wrap']/input[#type='text']")).sendKeys("9999999999");
//Enter password into the text box
driver.findElement(By.xpath("//div[#class='tmargin10 login-input-wrap']/input[#type='password']")).sendKeys("abcdefgh");
//wait for 30seconds
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
//click on Login button
driver.findElement(By.xpath("//div[#class='tmargin20 login-btn-wrap']/input[#type='button']")).click();
//wait for 30seconds
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
}
#Test(priority=1)
public void FlipkartSearch()
{
driver.findElement(By.xpath("//div[#id='container']//form//input[#type='text']")).sendKeys("Mobile");
FlipkartSerchfnctn("mobile");
}
#Parameters("mobile")
#Test(priority=2)
public void FlipkartSerchfnctn(#Optional("mobile") String textToSelect)
{
List <WebElement> listItems = driver.findElements(By.xpath(".//form[#class='_1WMLwI']//ul/li"));
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
for (int i = 0; i < listItems.size(); i++) {
System.out.println(listItems.get(i).getText());
if(listItems.get(i).getText().equals("mobile")){
System.out.println("Trying to select 2: "+textToSelect);
listItems.get(i).click();
break;
}
}
//#AfterTest
//public void tearDown() throws Exception {
// driver.quit();
//}
}
}
You are calling to FlipkartSerchfnctn() from test FlipkartSearch() and than execute it gain as independent test with the same parameters ("mobile"). That's why you get the results twice.
Either don't call it from test FlipkartSearch() or remove the #Test annotation from FlipkartSerchfnctn().
You can use the following XPATH query for getting an element based on text in it.
'//*[contains(text(), "some text present in element")]'
OR
'//YOUR XPATH TO THAT ELEMENT[contains(text(), "some text present in element")]'

Unable to click on Setting Icon in Gmail with selenium web-driver

This is what i am trying do on Gmail.
www.gmail.com
Login using a valid user (if does not exist create a dummy user)
Click on Inbox
Click on first email
Click on Compose Email.
Send the mail to the same email account.
Click on options icon on the top right corner
Got to vacation responder on the General settings tab
Select vacation responder to on.
I am able to click on 1st email and pick the email Address and then click on compose email button, also able to send the email.
The problem i am facing is unable to click on settings icon. The element is hidden, i am not able to click it. I tried it with customized-Xpath and also tried to click it with coordinates.
But it not working for me. Please can anyone help me on this.
import org.openqa.selenium.By;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Gmail1 {
public static void main(String[] args) throws InterruptedException {
// Login to browser
WebDriver driver= new FirefoxDriver();
driver.get("https://www.gmail.com");
driver.manage().window().maximize();
System.out.println("Browser opned");
driver.findElement(By.xpath("//*[#id='Email']")).sendKeys("Use your UserId");
System.out.println("Entered Email id");
driver.findElement(By.xpath("//*[#id='next']")).click();
System.out.println("Clicked on Next");
Thread.sleep(3000);
driver.findElement(By.xpath("//*[#id='Passwd']")).sendKeys("Use your password");
System.out.println("Entered the Password");
driver.findElement(By.xpath("//*[#id='signIn']")).click();
System.out.println("Welcome to gmail");
Thread.sleep(5000);
driver.findElement(By.xpath("//*[#id=':3d']")).click();
System.out.println("Clicked on email");
Thread.sleep(3000);
String emailid = driver.findElement(By.xpath("//span[#class='go']")).getText();
emailid=emailid.substring(emailid.indexOf("<")+1, emailid.indexOf(">"));
System.out.println(emailid);
driver.findElement(By.xpath("//*[#id=':it']/div/div")).click();
System.out.println("Clicked on Compose mail");
driver.findElement(By.xpath("//*[#name='to']")).sendKeys(emailid);
System.out.println("Entered the TO Email Address");
driver.findElement(By.xpath("//*[#name='subjectbox']")).sendKeys("My Mail");
System.out.println("Entered Subject of the email");
driver.findElement(By.xpath("//*[#role='button' and .='Send']")).click();
System.out.println("Clicked on send button");
clickSetting(driver);
}
public static void clickSetting(WebDriver driver){
//Tried with Coordinates (doesn't work)
Point point = driver.findElement(By.xpath("//div[#class='G-Ni J-J5-Ji'] [#gh ='s']/*[1]")).getLocation();
System.out.println(point.x + "-" + point.y);
Actions builder = new Actions(driver);
builder.moveByOffset(point.x, point.y).click().build().perform(); //Getting Error.
//Tried with Action Class (doesn't work)
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement SettingWheel=driver.findElement(By.xpath("//*[#data-tooltip='Settings' and #role='button']"));
WebElement SettingsLink=driver.findElement(By.xpath("//*[#role='menuitem']/div[.='Settings']"));
wait.until(ExpectedConditions.elementToBeClickable(SettingWheel));
Actions actions = new Actions(driver);
actions.moveToElement(SettingWheel).moveToElement(SettingsLink).click().build().perform();//Getting Error.
Thread.sleep(2000);
System.out.println("Clicked On Setting");
}
Error message:- "Element is not currently visible and so may not be interacted with (WARNING: The server did not provide any stacktrace information)"
Thanks in Advance.
Try this:-
public static void clickSetting(WebDriver driver){
List<WebElement> elements=driver.findElements(By.xpath("//div[#gh='s']/*[#role='button']"));
for(WebElement element:elements){
if(element.isDisplayed()){
element.click();
Thread.sleep(2000);
driver.findElement(By.xpath("//*[#id='ms']")).click();
Thread.sleep(5000);
}
}
The problem is with your xpath. I tried with id ad it worked. Thread.sleep is bad idea. Don't go with that and instead use WebDriverWait
Anyhow the following snippet will click on settings gear then settings and wait till the Settings panel is loaded completely
Also go through this Gmail Selenium and see how I've handled Gmail login without Thread.sleep
public static void clickSetting(WebDriver driver) {
WebDriverWait wait = new WebDriverWait(driver, 60);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[#id=':3d']"))).click();
System.out.println("Clicked On Settings Gear");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[#role='menuitem']/div[.='Settings']"))).click();
System.out.println("Clicked On Setting");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[#class='dt']")));
System.out.println("Settings Visible");
}
Try this:
package yourPackageName;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class TestClass2 {
static WebDriver driver;
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "c:/chromedriver.exe");
driver = new ChromeDriver();
Step_1_LaunchApp();
Step_2_LoginUsingCredentials();
Step_3_ClickOnInbox();
Step_4_ClickOnFirstEmail();
Step_5_ClickOnComposeEmail();
Step_6_ClickOnSettingsIcon();
}
private static void Step_6_ClickOnSettingsIcon() {
try{
driver.findElement(By.xpath("//*[#class='aos T-I-J3 J-J5-Ji']")).click();
}catch(Exception e){
e.printStackTrace();
}
}
private static void Step_5_ClickOnComposeEmail() {
try{
driver.findElement(By.xpath("//div[contains(text(),'COMPOSE')]")).click();
}catch(Exception e){
e.printStackTrace();
}
}
private static void Step_4_ClickOnFirstEmail() {
try{
driver.findElement(By.xpath("//div[#role='tabpanel'][1]//table//tr[1]")).click();
}catch(Exception e){
e.printStackTrace();
}
waitTimeInSecond(2);
}
private static void Step_3_ClickOnInbox() {
driver.findElement(By.xpath("//span/a[contains(text(),'Inbox')]")).click();
waitTimeInSecond(2);
}
private static void Step_2_LoginUsingCredentials() {
driver.findElement(By.id("Email")).sendKeys("email#gmail.com");
driver.findElement(By.id("next")).click();
waitTimeInSecond(2);
driver.findElement(By.id("Passwd")).sendKeys("Password");
driver.findElement(By.id("signIn")).click();
waitTimeInSecond(5);
}
private static void Step_1_LaunchApp() {
driver.get("http://gmail.com");
}
public static void waitTimeInSecond(int waitTime){
try{Thread.sleep(waitTime*1000);}catch(Exception e){}
}
}
.
Put your credentials first and run the script, it will click on settings gear.