Locating iFrames and controls within them using Selenium WebDriver - selenium

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

Related

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

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

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

isEnabled() failed to find element

I am new to selenium. I trying to check whether button is enable or not through isEnabled(). But when I am running this program it generating a error as "Unable to locate element" of button.
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;
public class test
{
static WebDriver driver;
public static void main(String[] args)
{
System.setProperty("webdriver.chrome.driver", "D:\\rakesh\\software\\selenium browser\\New folder\\chromedriver.exe");
driver=new ChromeDriver();
driver.get("https://app.crossover.com/");
driver.manage().window().maximize();
JavascriptExecutor js= (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0,5500)", "");
driver.findElement(By.linkText("Available Jobs")).click();
Boolean search_btn_ele = driver.findElement(By.xpath(".//*[#id='available-jobs']/div[2]/form/div/div[3]/button")).isEnabled();
if(search_btn_ele.FALSE)
{
System.out.println("Button is disable before giving search keys");
}
else
{
System.out.println("Button is enable before giving search keys");
}
WebElement search_txtfield_ele= driver.findElement(By.xpath(".//*[#id='available-jobs']/div[2]/form/div/div[1]/div/input"));
search_txtfield_ele.sendKeys("Chief");
}
}
Use WebDriverWait to wait for the element to be present:
new WebDriverWait(driver, TimeSpan.FromSeconds(45)).Until(ExpectedConditions.ElementIsVisible((By.Id("ctl00_ContentPlaceHolder1_drp85"))));

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")]'

how to get page content from any site using selenium?

Here is my code it return null value but is runs well in browser console
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.firefox.FirefoxDriver;
public class google {
public static void main(String[] args) throws Exception {
WebDriver driver = new FirefoxDriver();
driver.get("https://in.yahoo.com/");
JavascriptExecutor js;
js = (JavascriptExecutor)driver;
String scriptReturningString = "";
String scriptResult = (String)js.executeScript("return document.getElementsByTagName('body')[0].innerText");
System.out.println("Text Inside:"+scriptResult);
driver.quit();
}
}
WebDriver webDriver = new FirefoxDriver();
webDriver.get("https://in.yahoo.com/");
String content = webDriver.findElement(By.tagName("body")).getText();
System.out.println(content);
This code gets page's content (not source code), stores it in variable content and then prints it in console.
If you want to get page's source code you should use webDriver.getPageSource() method.