Automation Testing

How to automate gmail login process using selenium webdriver…


We can automate the Gmail login process using Selenium webdriver in Java. To perform this task, first we have to launch the Gmail login page and locate the email, password and other elements with the findElement method and then perform actions on them.

Let us have the look at the Gmail login page −

Code Implementation

package RK1.Building_a_selenium_project;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;

public class GmailLogin {

	public static void main(String[] args) {
		System.setProperty("webdriver.chrome.driver", "F:\\Work Environment\\MyProject\\QA_Round\\chromedriver.exe");
	      WebDriver driver = new ChromeDriver();
	      //implicit wait
	      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
	      //URL launch
	      driver.get("https://accounts.google.com/signin");
	      //identify email
	      WebElement l = driver
	      .findElement(By.name("identifier"));
	      l.sendKeys("abc@gmail.com");
	      WebElement b = driver
	      .findElement(By.className("VfPpkd-LgbsSe"));
	      b.click();
	      //identify password
	      WebElement p = driver
	      .findElement(By.name("password"));
	      p.sendKeys("123456");
	      b.click();
	      //close browser
	      driver.close();
	   }
	}
Automation Testing

How to automate instagram login page using java in…


We can automate Instagram login page with Selenium webdriver in Java. To achieve this, first we have to launch the Instagram login page and identify the elements like email, password and login with the findElement method and interact with them.

Let us have the look at the Instagram login page −

Code Implementation

package RK1.Building_a_selenium_project;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;

public class InstaLogin {

	public static void main(String[] args) {
		System.setProperty("webdriver.chrome.driver", "F:\\Work Environment\\MyProject\\QA_Round\\chromedriver.exe");
	      WebDriver driver = new ChromeDriver();
	      //implicit wait
	      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
	      //URL launch
	      driver.get("https://www.instagram.com/");
	      //identify username
	      WebElement l = driver
	      . findElement(By.name("username"));
	      l.sendKeys("test@gmail.com");
	      //identify password
	      WebElement p = driver
	      .findElement(By.name("password"));
	      p.sendKeys("test123");
	      WebElement b = driver
	      .findElement(By.className("Igw0E"));
	      b.click();
	      //obtain value entered for username
	      String s = l.getAttribute("value");
	      System.out.println("Value entered for username: " + s);
	      //quit browser
	      driver.quit();
	   }
	}


Output:

Starting ChromeDriver 97.0.4692.71 (adefa7837d02a07a604c1e6eff0b3a09422ab88d-refs/branch-heads/4692@{#1247}) on port 13129
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
Jan 19, 2022 11:39:02 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
Value entered for username: test@gmail.com

Automation Testing

How to Open New Browser Tab in Selenuim


Answer − We can open a new browser tab in Selenium webdriver. The methods – Keys.chord and sendKeys are required to achieve this task. The Keys.chord method is used to send multiple keys at once.

We shall pass Keys.CONTROL and Keys.ENTER as parameters to this method. The complete string is again passed as a parameter to the sendKeys. Finally, the method sendKeys shall be applied on the link which we want to open in a new tab

Syntax

String l = Keys.chord(Keys.CONTROL,Keys.ENTER);
driver.findElement(By.xpath("//*[text()='Links']")). sendKeys(l);

Code Implementation

package RK1.Building_a_selenium_project;

import java.util.concurrent.TimeUnit;

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

public class OpenNextTab {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.setProperty("webdriver.chrome.driver", "F:\\Work Environment\\MyProject\\QA_Round\\chromedriver.exe");

		WebDriver driver = new ChromeDriver();

		// wait of 5 seconds
	      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
	      //url launch
	      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
	      // Keys.Chord string
	      String l = Keys.chord(Keys.CONTROL,Keys.ENTER);
	      // open new tab
	      driver.findElement(By.xpath("//*[text()='Terms of Use']")).sendKeys(l);
	      driver.quit();
	   }

	}

Automation Testing

How to download all pdf files with selenium python?


Answer − We can download all pdf files using Selenium webdriver in Python. A file is downloaded in the default path set in the Chrome browser. However, we can modify the path of the downloaded file programmatically in Selenium.

This is done with the help of the Options class. We have to create an object of this class and apply add_experimental_option. We have to pass the parameters – prefs and the path where the pdf is to be downloaded to this method. Finally, this information has to be sent to the webdriver object.

Syntax

op = Options()
p = {"download.default_directory": "../pdf"}
op.add_experimental_option("prefs", p)

Example

Code Implementation

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
#Options instance
op = Options()
#configure path of downloaded pdf file
p = {"download.default_directory": "../pdf"}
op.add_experimental_option("prefs", p)
#send browser option to webdriver object
driver = webdriver.Chrome(executable_path='F:\\Work Environment\\MyProject\\QA_Round\\chromedriver.exe',
options=op)
#implicit wait
driver.implicitly_wait(0.8)
#url launch
driver.get("http://demo.automationtesting.in/FileDownload.html")
#browser maximize
driver.maximize_window()
#identify element
m = driver.find_element_by_id('pdfbox')
m.send_keys("infotest")
t = driver.find_element_by_id('createPdf')
t.click()
e = driver.find_element_by_id('pdf-link-to-download')
e.click()
#driver close
driver.close()

Automation Testing

How can I capture network traffic of a specific…


We can capture network traffic on a specific page using Selenium webdriver in Python. To achieve this, we take the help of the JavaScript Executor. Selenium can execute JavaScript commands with the help of the execute_script method.

JavaScript command to be executed is passed as a parameter to this method. To capture the network traffic, we have to pass the command: return window.performance.getEntries() as a parameter to the execute_script method.

Syntax

r = driver.execute_script("return window.performance.getEntries();")

Example

Code Implementation





from selenium import webdriver
#configure chromedriver path
driver = webdriver.Chrome(executable_path='F:\\Work Environment\\MyProject\\QA_Round\\chromedriver.exe')
#implicit wait
driver.implicitly_wait(0.5)
#url launch
driver.get("https://www.google.com/")
#JavaScript command to traffic
r = driver.execute_script("return window.performance.getEntries();")
for res in r:
    print(res['name'])
#browser close
driver.close()

Output:

DevTools listening on ws://127.0.0.1:56201/devtools/browser/4da6ea83-b808-4ec5-8ae3-5d9a644abfe6
https://www.google.com/
https://www.google.com/xjs//js/k=xjs.s.en_GB.jS3OP7-RYWo.O/am=CCgA2EAAAAQzAAAAAAAAAIBA4MEAIAASSQAAAAAAQQAARACXAwQAAADwEZ8BAv4GAEbQhAsAAAAAAAAIwCXFUINEQQAIAAAAABCrqSsGgEAg/d=1/ed=1/dg=2/esmo=1/br=1/rs=ACT90oHGOS_vgEofFOFQIJLil3vVNM6d2g/m=cdos,dpf,hsm,jsa,d,csi https://www.google.com/logos/doodles/2022/get-vaccinated-wear-a-mask-save-lives-january-17-copy-6753651837109683-law.gif https://www.google.com/images/searchbox/desktop_searchbox_sprites318_hr.webp first-paint first-contentful-paint https://www.gstatic.com/og//js/k=og.qtm.en_US.9pElbIcw614.O/rt=j/m=qabr,q_dnp,qcwid,qapid,qald/exm=qaaw,qadd,qaid,qein,qhaw,qhbr,qhch,qhga,qhid,qhin,qhpr/d=1/ed=1/rs=AA2YrTsg7Vn-zTR579BY_X_YWcvF5v0w8g
https://www.gstatic.com/og//ss/k=og.qtm.ofT4jE96td0.L.W.O/m=qcwid/excm=qaaw,qadd,qaid,qein,qhaw,qhbr,qhch,qhga,qhid,qhin,qhpr/d=1/ed=1/ct=zgms/rs=AA2YrTvubo9qkY4L_hGiF_giXJgemAw0Bw https://www.google.com/gen_204?s=webhp&t=aft&atyp=csi&ei=XfzmYcrbD7WD4-EP-PSZwAY&rt=wsrt.1279,aft.212,afti.212,prt.188&imn=2&ima=1&imad=0&aftp=620&bl=UJOX O7jPNb kDcP9b https://www.google.com/complete/search?q&cp=0&client=gws-wiz&xssi=t&hl=en-IN&authuser=0&psi=XfzmYcrbD7WD4-EP-PSZwAY.1642527829192&nolsbt=1&dpr=1 https://www.google.com/xjs//js/k=xjs.s.en_GB.jS3OP7-RYWo.O/ck=xjs.s.O9zdDYGJ4io.L.W.O/am=CCgA2EAAAAQzAAAAAAAAAIBA4MEAIAASSQAAAAAAQQAARAC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w86d:dt4g2b;lkq0A:Z0MWEf;eHDfl:ofjVkb;SNUn3:x8cHvb;LEikZe:byfTOb,lsjVmc;io8t5d:sgY6Zb;j7137d:KG2eXe;Oj465e:KG2eXe;sP4Vbe:VwDzFe;kMFpHd:blwjVc/m=DhPYme,EkevXb,GU4Gab,NzU6V,aa,abd,async,dvl,fKZehd,mu,pHXghd,sb_wiz,sf,sonic,spch?xjs=s1
https://www.google.com/client_204?&atyp=i&biw=1034&bih=575&ei=XfzmYcrbD7WD4-EP-PSZwAY
https://www.google.com/xjs//js/k=xjs.s.en_GB.jS3OP7-RYWo.O/ck=xjs.s.O9zdDYGJ4io.L.W.O/am=CCgA2EAAAAQzAAAAAAAAAIBA4MEAIAASSQAAAAAAQQAARACXAwQAAADwEZ8BAv4GAEbQhAsAAAAAAAAIwCXFUINEQQAIAAAAABCrqSsGgEAg/d=1/exm=DhPYme,EkevXb,GU4Gab,NzU6V,aa,abd,async,cdos,csi,d,dpf,dvl,fKZehd,hsm,jsa,mu,pHXghd,sb_wiz,sf,sonic,spch/esmo=1/ed=1/dg=2/br=1/rs=ACT90oEY3toiTZYMSoFCT5U_006iXLyKLw/ee=yxTchf:KUM7Z;qddgKe:x4FYXe;uY49fb:COQbmf;wR5FRb:TtcOte;iFQyKf:QIhFr;dIoSBb:ZgGg9b;eBAeSb:Ck63tb;g8nkx:U4MzKc;wQlYve:aLUfP;kbAm9d:MkHyGd;F9mqte:UoRcbe;sTsDMc:kHVSUb;vfVwPd:OXTqFb;dtl0hd:lLQWFe;q92ire:wPVhqc;pXdRYb:JKoKVe;KpRAue:Tia57b;EVNhjf:pw70Gc;nAFL3:s39S4;LQlyHd:KJbvFf;aZ61od:arTwJ;JXS8fb:Qj0suc;rQSrae:C6D5Fc;qavrXe:zQzcXe;pNsl2d:j9Yuyc;UDrY1c:eps46d;nKl0s:xxrckd;Nyt6ic:jn2sGd;w3bZCb:ZPGaIb;imqimf:jKGL2e;KQzWid:mB4wNe;Np8Qkd:Dpx6qc;BjwMce:cXX2Wb;oGtAuc:sOXFj;whEZac:iuHkw;Fmv9Nc:O1Tzwc;hK67qb:QWEO5b;jVtPve:wQ95P;R4IIIb:QWfeKf;xbe2wc:wbTLEd;tosKvd:ZCqP3;NSEoX:lazG7b;kCQyJ:ueyPK;oSUNyd:fTfGO;SJsSc:H1GVub;SMDL4c:fTfGO;NPKaK:PVlQOd;zOsCQe:Ko78Df;WCEKNd:I46Hvd;LBgRLc:XVMNvd;TxfV6d:YORN0b;GleZL:J1A7Od;qaS3gd:yiLg6e;VGRfx:VFqbr;aAJE9c:WHW6Ef;BgS6mb:fidj5d;z97YGf:oug9te;CxXAWb:YyRLvc;Pguwyb:Xm4ZCd;VN6jIc:ddQyuf;SLtqO:Kh1xYe;WDGyFe:jcVOxd;DULqB:RKfG5c;gaub4:TN6bMe;DpcR3d:zL72xf;hjRo6e:F62sG;w9w86d:dt4g2b;lkq0A:Z0MWEf;eHDfl:ofjVkb;SNUn3:x8cHvb;LEikZe:byfTOb,lsjVmc;io8t5d:sgY6Zb;j7137d:KG2eXe;Oj465e:KG2eXe;sP4Vbe:VwDzFe;kMFpHd:blwjVc/m=LtQuz,VsqSCc,fXO0xe,kQvlef?xjs=s2 https://www.google.com/gen_204?atyp=i&ei=XfzmYcrbD7WD4-EP-PSZwAY&dt19=2&zx=1642527829299 https://www.google.com/client_204?cs=1 https://apis.google.com//scs/abc-static//js/k=gapi.gapi.en.h3Hb0D_ghuM.O/m=gapi_iframes,googleapis_client/rt=j/sv=1/d=1/ed=1/rs=AHpOoo8HKYs3uYwO3D8vrT9sPLRNofSg0A/cb=gapi.loaded_0 https://www.google.com/xjs//js/k=xjs.s.en_GB.jS3OP7-RYWo.O/ck=xjs.s.O9zdDYGJ4io.L.W.O/am=CCgA2EAAAAQzAAAAAAAAAIBA4MEAIAASSQAAAAAAQQAARACXAwQAAADwEZ8BAv4GAEbQhAsAAAAAAAAIwCXFUINEQQAIAAAAABCrqSsGgEAg/d=1/exm=DhPYme,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d:zL72xf;hjRo6e:F62sG;w9w86d:dt4g2b;lkq0A:Z0MWEf;eHDfl:ofjVkb;SNUn3:x8cHvb;LEikZe:byfTOb,lsjVmc;io8t5d:sgY6Zb;j7137d:KG2eXe;Oj465e:KG2eXe;sP4Vbe:VwDzFe;kMFpHd:blwjVc/m=aLUfP?xjs=s2

In Java:

package RK1.Building_a_selenium_project;

import org.testng.annotations.Test;

import java.util.Date;
import java.util.List;
import java.util.logging.Level;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.logging.LoggingPreferences;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.Reporter;
import org.testng.annotations.AfterTest;

public class NetworkState {
	public static WebDriver driver;

  @SuppressWarnings("deprecation")
@Test
  public void test1() {
	  System.setProperty("webdriver.chrome.driver", "F:\\Work Environment\\MyProject\\QA_Round\\chromedriver.exe");

	  DesiredCapabilities caps = DesiredCapabilities.chrome();
	  ChromeOptions options = new ChromeOptions();
	  LoggingPreferences logPrefs = new LoggingPreferences();
	  logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
	  options.setCapability( "goog:loggingPrefs", logPrefs );

	  caps.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
	  driver = new ChromeDriver(caps);
	  
	  
	  driver.navigate().to("https://www.google.com/");
	  List<LogEntry> entries = driver.manage().logs().get(LogType.BROWSER).getAll();

	  System.out.println(entries.size() + " " + LogType.PERFORMANCE + " log entries found");

	  for (LogEntry entry : entries) {
	      System.out.println(new Date(entry.getTimestamp()) + " " + entry.getLevel() + " " + entry.getMessage());

  }
  }
  
  @AfterTest
  public void afterTest() {
	  driver.close();
	  driver.quit();
	  Reporter.log("Test is complete: Exit");
  }
  


}
Automation Testing

What is the difference between findElement and findElements in…


There are differences between findElement and findElements in the Selenium webdriver. Both of them can be used to locate elements on a webpage. The findElement points to a single element, while the findElements method returns a list of matching elements.

The return type of findElements is a list but the return type of findElement is a WebElement. If there is no matching element, a NoSuchElementException is thrown by the findElement, however, an empty list is returned by the findElements method.

Good usage of the findElements method usage is counting the total number of images or accessing each of images by iterating with a loop.

Syntax −

WebElement i = driver.findElement(By.id("img-loc"));
List<WebElement> s =
driver.findElements(By.tagName("img"));

Example

Code Implementation

import org.openqa.selenium.By;
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 FindElementFindElementMthds{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();

      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

      //URL launch
      driver.get("https://www.tutorialspoint.com/upsc_ias_exams.htm");

      //identify single element
      WebElement elm = driver.findElement(By.tagName("h2"));
      String s = elm.getText();
      System.out.println("Get text on element: " + s);

      //identify all elements with tagname
      List<WebElement> i = driver.findElements(By.tagName("img"));

      //count
      int c = i.size();
      System.out.println("Number of images: " + c);

      //browser close
      driver.close();
   }
}
Automation Testing

Clear text from text area using selenium WebDriver.


We can clear text from the text area using Selenium webdriver. We shall use the clear method to remove the content from a text area or an edit box. First, we shall identify the text area with the help of any locator.

A text area is identified with a textarea tagname in the html code. Let us input some text inside the below text area, then clear the text.

Example

Code Implementation

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class TextAreaClear{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6ko r\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();

      //URL launch
      driver.get("http://www.uitestpractice.com/Students/Form");

      // identify element
      WebElement m = driver.findElement(By.id("comment"));

      // enter text
      m.sendKeys("Selenium");

      // obtain value entered in text area
      System.out.println("Value entered: " + m.getAttribute("value"));

      // clear text area
      m.clear();

      // obtain value entered in text area after clear applied
      System.out.println("Value after clear(): " + m.getAttribute("value"));

      //browser close
      driver.close();
   }
}
Automation Testing

How to maximize or minimize a browser window using…


We can maximize or minimize a browser window using Selenium webdriver in Python. We can use the method maxmize_window to maximize a browser.

We can use the method minimize_window to minimize a browser. Finally, Again, to get the size of the browser, we can use the method get_window_size.

Syntax

driver.maximize_window()
driver.minimize_window()

Example

Code Implementation

from selenium import webdriver
#set geckodriver.exe path
driver = webdriver.Firefox(executable_path="C:\\geckodriver.exe")
#implicit wait
driver.implicitly_wait(5)
#launch URL
driver.get("https://www.tutorialspoint.com/index.htm")
#maximize browser
driver.maximize_window()
#minimize browser
driver.minimize_window()
#quit browser
driver.quit()

Automation Testing

How to click on a link using Selenium webdriver…


We can click on a link using Selenium webdriver in Python. A link is represented by the anchor tag. A link can be identified with the help of the locators like – link text and partial link text.

We can use the link text attribute for an element for its identification and utilize the method find_element_by_link_text. With this, the first element with the matching value of the given link text is returned.

Syntax

driver.find_element_by_link_text("value of link text")

We can also use the partial link text attribute for an element for its identification and utilize the method find_element_by_partial_link_text. With this, the first element with the matching value of the given partial link text is returned.

For both the locators, if there is no element with the matching value of the partial link text/link text, NoSuchElementException shall be thrown.

Syntax

driver.find_element_by_partial_link_text("value of partial ink text")

Let us see the html code of a webelement −

The link highlighted in the above image has a tagname – a and the partial link text – Refund. Let us try to click on this link after identifying it.

Example

Code Implementation

from selenium import webdriver
driver = webdriver.Chrome(executable_path='../drivers/chromedriver')
#url launch
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
#identify link with partial link text
l = driver.find_element_by_partial_link_text('Refund')
#perform click
l.click()
print('Page navigated after click: ' + driver.title)
#driver quit
driver.quit()

Output

Automation Testing

How to get the total number of radio buttons…


We can get the total number of radio buttons on a page using Selenium webdriver using the find_elements method. While working on any radio buttons, we will always find an attribute type in the html code and its value should be radio.

This characteristic is only applicable to radio buttons on that particular page and to no other types of UI elements like edit box, link, and so on.

To retrieve all the elements with attribute type = ‘radio’, we will use find_elements_by_xpath() method. This method returns a list of web elements with the type of xpath specified in the method argument. In case there are no matching elements, an empty list will be returned.

After the list of radio buttons is fetched, in order to count its total numbers, we need to get the size of that list. The size of the list can be obtained from the len() method of the list data structure.

Finally, this length is printed on the console.

Syntax

driver.find_elements_by_xpath("//input[@type='radio']")

Example

Code Implementation for counting radio buttons.

from selenium import webdriver
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/selenium/selenium_automation_practice.htm")
#to refresh the browser
driver.refresh()
# identifying the radio buttons with type attribute in a list
chk =driver.find_elements_by_xpath("//input[@type='radio']")
# len method is used to get the size of that list
print(len(chk))
#to close the browser
driver.close()