Automation Testing

How to retrieve all options in a dropdown using…


We can retrieve all options in a dropdown using Selenium. All the options in the dropdown are stored in a list data structure. This is achieved with the help of options() which is a method under the Select class.

options() returns a list of all options under the select tag. An empty list is returned if the dropdown is not identified on the page with the help of any of the locators.

Syntax

d = Select(driver.find_element_by_id("selection"))
o = d.options()

Example

Code Implementation for getting all options in the dropdown.

from selenium import webdriver
from selenium.webdriver.support.select import Select
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")

# to maximize the browser window
driver.maximize_window()

#get method to launch the URL
driver.get("https://www.tutorialspoint.com/tutor_connect/index.php")

#to refresh the browser
driver.refresh()

#select class provide the methods to handle the options in dropdown
d = Select(driver.find_element_by_xpath("//select[@name='seltype']"))

#store the options in a list with options method
l = d.options

#to count the number of options and print in console
print(len(l))

#to get all the number of options and print in console
for i in l:
print(i.text)

#to close the browser
driver.close()

Automation Testing

How to scroll down a webpage in selenium using…


We can scroll down a webpage in Selenium using Java. Selenium is unable to handle scrolling directly. It takes the help of the Javascript Executor to perform the scrolling action up to an element.

First of all, we have to locate the element up to which we have to scroll. Next, we shall use the Javascript Executor to run the Javascript commands. The method executeScript is used to run Javascript commands in Selenium. We shall take the help of the scrollIntoView method in Javascript and pass true as an argument to the method.

Syntax −

WebElement elm = driver.findElement(By.name("name"));
((JavascriptExecutor) driver)
.executeScript("arguments[0].scrollIntoView(true);", elm);

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class ScrollAction{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
      //launch application
      driver.get
      ("https://www.tutorialspoint.com/about/about_careers.htm ");
      // identify element
      WebElement n=driver.findElement(By.xpath("//*[text()='Contact']"));
      // Javascript executor
      ((JavascriptExecutor)driver)
      .executeScript("arguments[0].scrollIntoView(true);", n);
   }
}
Automation Testing

What are the differences between get() and navigate() method?


The differences between get() and navigate() methods are listed below.

sl.no.get()navigate()
1It is responsible for loading the page and waits until the page has finished loading.It is only responsible for redirecting the page and then returning immediately.
2It cannot track the history of the browser.It tracks the browser history and can perform back and forth in the browser.

Example

With get().

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
public class LaunchBrw {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      driver.close();
   }
}

Example

With navigate().

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
public class BrowserNavigation {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      // new browser will launch and navigate to the URL
      driver.navigate().to(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      // refresh the current browser
      driver.navigate().refresh();
      //Using id tagname attribute combination for css expression
      driver.findElement(By.cssSelector("input[name=’search’]")). sendKeys("Selenium");
      //browser will go back to the previous page
      driver.navigate().back();
      //browser will go move to the next page
      driver.navigate().forward();
      driver.close();
   }
}
Automation Testing

How to perform search in amazon using selenium.

Solution:

  1. Create a new Project in Eclipse.
  2. Add the required libraries for Selenium.

Now in first you need to create an interface: driver

import org.apache.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.remote.DesiredCapabilities;

public interface driver {
	
	public  WebDriver wd = new FirefoxDriver();
	public static String baseURL = "http://automationpractice.com/index.php";
	public static String driverPath = "F:\\Work Environment\\MyProject\\gekodriver\\geckodriver.exe";
	public void CallDriver();
	public static String email = "rahul@gmail.com";
	public static String password = "pass1234";
	public static Logger log  = Logger.getLogger(driver.class.getName());
	public static WebElement mainMenu = null;
	public static Action actions = null;
}

Now create a new TestNG Class and enter the following script:

import org.testng.annotations.Test;
import org.testng.annotations.BeforeTest;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.annotations.AfterTest;

public class Search1 implements driver {
	public static WebElement se;
  
  @BeforeTest
  public void CallDriver() {
	  
	  System.setProperty("webdriver.gecko.driver",driverPath );
	  wd.manage().window().maximize();
	  wd.get("https://www.amazon.com/");
	  log.debug("Navigated to Amazon.com");
  }
  
  @Test
  public void TestSearch() {
	  WebElement se = wd.findElement(By.id("twotabsearchtextbox"));
	  se.sendKeys("iphone");
	  log.debug("Entered a keyword to search");
	  
	  wd.findElement(By.id("nav-search-submit-button")).click();
	  log.debug("Search button is clicked");
	  
	  
  }
  
  @Test
  public void TestSearch1() {
	  
	  String actRe = wd.getCurrentUrl();
	  String exres = "https://www.amazon.com/s?k=iphone&ref=nb_sb_noss_2";
		  Assert.assertEquals(actRe,exres);
	  se.clear();  
  }
  
  @Test
  public void TestSearch2() {
	  wd.navigate().back();
	  log.debug("nvigated back to previous page");
	 System.out.println(wd.getCurrentUrl());
  }
  

  @AfterTest
  public void afterTest() {
	  wd.quit();
  }


}

Automation Testing

Automation Code Test 1

Core Automation: 

Navigate to https://blazedemo.com/index.php  

  1. Check if the title is displayed as ` Welcome to the Simple Travel Agency!`. This is the Home Page of application 
  1. Click on ` destination of the week! The Beach!` hyperlink and see if a new tab opens in your browser & the url has string `vacation`. Navigate back to home page tab. 
  1. Purchase a ticket:  
  1. Select `Mexico City` in departure city & `London` in destination city.  
  1. Click ‘Find Flights’. Select the flight with lowest price by clicking `Choose the flight` & see if we are navigated to purchase page (This should be dynamically handled and can work for any inputs in Step 3.a) 
  1. Check if a field named ‘Total Cost’ is available with price available in xxx.xx format. Click on ‘Purchase flight’ button 
  1. Check if the user is navigated to Purchase Confirmation page & store the `Id’ in the console or test report for future reference. 

POINTS TO CONSIDER: 

  • Create a new Java, Maven, C# project with an appropriate test framework like Nunit, TestNG etc., 
  • Automate tests in Chrome browser 
  • Use parameterized data instead of hardcoded test data 
  • Use Page Object Model with Selenium 
  • Make your functions more generic and use coding best practices as much as possible 
  • Once the test is done, please zip the entire project and send it to us 

Solution:

  1. Create a new Project in Eclipse.
  2. Add the required libraries for Selenium.

Now in first you need to create an interface: driverHelp

import java.util.Properties;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public interface driverHelp {
	
	public static WebDriver wd = new ChromeDriver();
	public static String cd1 = "F:\\Work Environment\\MyProject\\chromedriver.exe";
	public static String url = "https://blazedemo.com/index.php";
	
}

Once you create the interface, you need to create a new class “DemoTest” and implement the interface driverHelp.

Add the following code in your class file and run as TestNG project.

import org.testng.annotations.Test;
import org.testng.annotations.BeforeTest;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.annotations.AfterTest;
import org.openqa.selenium.support.ui.Select;

public class DemoTest implements driverHelp {
	
	public static WebElement we1;
  
  @BeforeTest
  public void callDriver() {
	  System.setProperty("webdriver.chrome.driver", cd1);
	  wd.manage().deleteAllCookies();
	  wd.manage().window().maximize();
	  wd.get(url);
  }
  
  
  @Test
  public void Test1() {
	 System.out.println(wd.getTitle());
	 
	 String t1 = "Welcome to the Simple Travel Agency!";
	 if(t1.equals(wd.getTitle()) ) {
		 System.out.println("Title Matched the expected result");
		 
	 }
	 
  }
	 
	 @Test
	  public void Test2() {
		wd.findElement(By.linkText("destination of the week! The Beach!")).click();
		System.out.println(wd.getCurrentUrl());
		wd.navigate().back();
		System.out.println(wd.getCurrentUrl());
			 
		 } 
	 
	 @Test
	  public void Test3() {
		 
		//d.findElement(By.className("form-inline")).click();
		 //.findElement(By.partialLinkText("Mexico City")).click();
		 
		 Select scity = new Select(wd.findElement(By.className("form-inline")));
		 scity.selectByVisibleText("Mexico City");
		 scity.selectByIndex(4);
		 
		 Select ecity = new Select(wd.findElement(By.name("toPort")));
		 ecity.selectByVisibleText("London");
		 ecity.selectByIndex(2);
		 
		 wd.findElement(By.xpath("/html/body/div[3]/form/div/input")).click();
		 
		 
	 }
	 
	 @Test
	  public void Test4() {
		 
		 wd.findElement(By.xpath("/html/body/div[2]/table/tbody/tr[3]/td[1]/input")).click();
		 System.out.printf("Flight with the lowest fair",wd.getTitle());
		 
	 }
	 
	 @Test
	  public void Test5() {
		 
		if( wd.findElement(By.partialLinkText("Total Cost")).isDisplayed())
		{
			System.out.println("Total Coast is present");
		}
		 
		 
	 }
	  
	 @Test
	  public void Test6() {
		 
		wd.findElement(By.xpath("/html/body/div[2]/form/div[11]/div/input")).click();
		System.out.println(wd.getCurrentUrl());
		 
	 }
	  
	  
	 

  @AfterTest
  public void afterTest() {
	  wd.quit();
  }

}

Automation Testing

Creating a Automated script in Python

This is the starting of our Selenium automation with Python.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.expected_conditions import presence_of_element_located

driver = webdriver.Chrome(executable_path="E://python tutorial//selenium_demo//chromedriver.exe")

driver.get("http://demo.guru99.com/test/newtours/")

print(driver.title)

driver.close()

For executing this script you will be required to Install Python, Selenium and Visual Studio Code (you can also use Pycharm)

“driver = webdriver.Chrome(executable_path=”E://python tutorial//selenium_demo//chromedriver.exe”)”

Here in this step we are providing the path of our chromedriver.exe

“driver.get(“http://demo.guru99.com/test/newtours/”)”

The above step consist of get(), this method is responsible for opening the URL in Browser.

print(driver.title) By using this step you can easily print the title of your application in test.

Once the test is completed you can close the application by using driver.close()

sss@DESKTOP-915O4CC MINGW64 /e/python tutorial/selenium_demo
$ [11924:11424:0413/142136.932:ERROR:device_event_log_impl.cc(214)] [14:21:36.932] Bluetooth: bluetooth_adapter_winrt.cc:712 GetBluetoothAdapterStaticsActivationFactory failed: Class not registered (0x80040154)
[11924:11424:0413/142137.037:ERROR:device_event_log_impl.cc(214)] [14:21:37.036] USB: usb_device_handle_win.cc:1056 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)
python sampleTest01.py

DevTools listening on ws://127.0.0.1:55122/devtools/browser/65f31bf4-da7a-41a0-8743-8d9516859d7f
[1812:11504:0413/142151.565:ERROR:device_event_log_impl.cc(214)] [14:21:51.564] Bluetooth: bluetooth_adapter_winrt.cc:712 GetBluetoothAdapterStaticsActivationFactory failed: Class not registered (0x80040154)
[1812:11504:0413/142151.666:ERROR:device_event_log_impl.cc(214)] [14:21:51.666] USB: usb_device_handle_win.cc:1056 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)
Welcome: Mercury Tours

This is the Output for your test.