Selenium with Python Tutorial | TECHLISTIC




1. What is Selenium WebDriver?

Selenium Webdriver is what world is talking about. Selenium Webdriver is web automation tool which is used for web functional testing. It supports different languages like Java, Python, C#, PHP, Ruby and Perl. WebDriver is now an official W3C Specification, and in-short, it is a method of interacting with a web browser. Previously, with Selenium RC, Selenium would operate with the browser by injecting JavaScript to interact with elements. With the adoption of WebDriver, browser manufacturers like Google, Mozilla, and Microsoft release their browser with the ability to be controlled by a hook, that Selenium can tap into. 

This hook enables Selenium to interact with the web browser in the same way that humans do.


Selenium with Python Video Tutorial (YouTube)



2. Features of Selenium WebDriver

1. Opensource/FreewareSelenium is free of cost. It means you do not have to buy any license like other software or do not have to pay to anyone for using Selenium for automation testing.
2. Web Functional FrameworkSelenium can only be used for automation testing of web applications/website. It is a functional testing tool so we can only automate functional test cases.
3. Multi-Language SupportIt is one of the major benefits of Webdriver. Selenium Webdriver supports many languages like Java, Python, PHP, C#, Ruby, Perl etc. So, it provides the flexibility to automation test engineers to automate test cases using any one language that they are comfortable.
4. Cross OS SupportSelenium supports multiple OS like, Windows, Linux, Unix, Mac. So if you have written webdriver automation code using windows platform, then same automation code could be used on other OS platforms like Unix, Linux, Mac.
5. Cross-Browser Compatibility TestingSelenium Webdriver supports almost every browser like Chrome, FF, Safari, Opera, IE and their versions. You can execute same automation scripts on different browsers for compatibility testing.

6. Cross Device Testing: Appium, which is a mobile automation tool is actually build on the top of Selenium Webdriver apis. In simple words Appium is another form of Webdriver to  e used for automation testing of mobile  applications.
7. Huge Community SupportThere is a huge community support for Selenium. A lot of tech professionals are contributing in building Selenium as the best automation tool.
8. Integrated with Multiple Frameworks/Tools: Selenium Webdriver can be integrated with various frameworks and tools like, Maven, Ant for compiling source code, with unit testing frameworks like TestNG for application testing and reporting and with Jenkins for Continuous Integration or Continuous Delivery, automated build and deployment.
9. Integration Support with other Automation Tools: It also gives the flexibility to integrate Java or Python modules, other automation tools like Sikuli, AutoIT for your automation needs.


3. Selenium Variants

There are 4 different variants of Selenium, which are:

1. Selenium IDE 
It’s a record and play tool, comes as plugin with Firefox only. No coding is required if you want to automate using this tool. But it can only be used for some very basic automation. As you cannot write your own logic or you won’t be able to put conditions or loops in your automation test script.

2. Selenium RC
RC stands for remote control. We have to write code using RC and it supports a number of languages. But it’s outdated now and there is no support available for RC.

3. Selenium Webdriver
Selenium Webdriver is web automation tool which can be used with different languages like Java, Python, C#, PHP, Ruby, Perl etc. It’s the successor of RC. Different architecture as what RC had (Not going in details).

4. Selenium Grid
Used for parallel execution of test cases (not an automation tool)


4. How does Selenium work?



5. Setup and Install Selenium Webdriver and Python


1. Download and Install the latest version of Python from below link -

2. Download and Install PyCharm (Community Edition) - ​PyCharm is a Python IDE which used to write python code.



3. Install Selenium​ module in Python -
  • Open command prompt and type following command in it and press enter
  • pip3 install –U selenium​
  • You can get all the information regarding Selenium's latest pypi package here - https://pypi.org/project/selenium/



4. Download ChromeDriver and GeckoDriver - Browser drivers are required to execute your Selenium code, if you want to execute your code on on chrome then you would have to download chromedriver and if you want to execute your Selenium script on firefox then you would need geckodriver. You can download drivers from following links -


  • After downloading the drivers, place them alongside your Selenium scripts.



6. Selenium Locators



7. Selenium with Python Commands

Let's take a look at the main Selenium Python commands which are used to automate any website/ web application.

1. Import Webdriver
First thing to do in any Selenium script is to import webdriver package. Only after importing webdriver, you can access all the functionality and commands of the webdriver.

Syntax:
from selenium import webdriver


2. Browser Command
We use browser command to launch any browser which we want to use for automation testing. And along with browser class we have to give path of the browser driver. Like in the following example we have created object of webdriver and initialized it with Chrome browser class and we have passed the path of the chromedriver to the constructor of Chrome class. Following line of code will launch the chrome browser session.

Syntax for initializing webdriver object with Chrome browser class:
browser = webdriver.Chrome("chromedriver.exe")
Syntax for launching firefox browser:
browser = webdriver.Firefox("geckodriver.exe")


3. Open URL command
This command is used to open the website URL which we want to test, get() command is used for this purpose. And get() command is called with webdriver object which browser and . (dot) operator.

Syntax to Get URL command:
browser.get('http://selenium.dev/')

4. Maximize Browser Window Command
This command is used to maximize the browser window which is opened by Selenium Webdriver.

Syntax for maximize browser window:
self.driver.maximize_window()


5. Implicit Wait Command
It is used to wait for a particular time interval generally seconds, before throwing "Element not found" exception. So, if the user has set implicit wait of 30 secs then Selenium webdriver will wait for maximum of 30 seconds for the element under action, if that element does not appear on the web page in 30 seconds, then Selenium will fail the script and throw the "Element not found" exception.

Syntax for implicit wait:
browser.implicitly_wait(30)


6. Find Element Command
This command is used to locate the element on the webpage so that Selenium Webdriver can perform the desired action on that element like., enter text inside the text box, click on the radio button or checkbox or click on the button etc. Find Element command is used along with the locator of the element like., id, class, name, xpath or css selector etc. For e.g., in the sample code we have located a text box with it's id value "firstName".

Syntax for Find Element Command:
browser.find_element(By.ID,'firstName')

Syntax for other Find Element Commands are:
browser.find_element(By.CLASS_NAME, 'search')
browser.find_element(By.NAME, 'lastName')
browser.find_element(By.LINK_TEXT, 'Selenium Tutorial')
browser.find_element(By.PARTIAL_LINK_TEXT, 'Tutorial')
browser.find_element(By.TAG_NAME, 'select')
browser.find_element(By.XPATH, "//*[contains(text(),'Music')]")
browser.find_element(By.CSS_SELECTOR, '#code2 > textarea')


7. Send Keys Command (Enter Text)
This command is used to enter text in any text box, text area, date picker etc. It is used along with find element command. In the example code, we are entering text "Jassi" in a text box using send_keys() command.

Syntax for Enter Text command is send_keys():
browser.find_element(By.ID,'firstName').send_keys("Jassi")


8. Click Command
Click command is used for various purposes, like for checking radio button, for selecting check box and for clicking a button or clicking on a link. This command is also used with find element command.

Syntax for clicking on a link "Selenium Tutorial":
browser.find_element(By.LINK_TEXT, 'Selenium Tutorial').click()


9. Quit Command
This command is used close all the browsers opened by the Selenium Webdriver. It is generally used in the end of the Selenium script to close the browser.

Syntax to Close Browser Command:
browser.quit()


7.1. Demo Scripts


7.1.1. Launch selenium.dev Script

This demo script will open the chrome browser and open the selenium.dev website.

from selenium import webdriver

browser = webdriver.Chrome("chromedriver.exe")
browser.get('http://selenium.dev/')


7.1.2. Search keyword "Selenium" in pypi.org search box

In this script, we'll launch chrome browser, open pypi.org and then type ""Selenium" in the search bar and will click enter.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

# Launch Chrome browser
browser = webdriver.Chrome("chromedriver.exe")
# Open pypi.org
browser.get('https://pypi.org/project/selenium/')

# Maximize Browser Window
browser.maximize_window()

# Set wait time of 30 secs
browser.implicitly_wait(30)

# Type "Selenium" in search bar
browser.find_element(By.ID, 'search').send_keys("Selenium")
# Click Enter
browser.find_element(By.ID, 'search').send_keys(Keys.RETURN)


7.1.3. Automate Techlistic Demo Sign-up form

In this demo script, we have automated Techlistic.com's demo sign-up form using all the Selenium Webdriver commands. And in this script unittest framework has been used. The setUp and tearDown methods are part of unittest framework in Python. SetUp method executes before the test method and tearDown method executes after the test method.

import time
import unittest

from selenium import webdriver
from selenium.webdriver.common.by import By

# Variables
driver_path='chromedriver.exe'
navigate_url = "https://www.techlistic.com/p/selenium-practice-form.html"

class DemoqaTesting(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Chrome(driver_path)
        self.driver.maximize_window()
        self.driver.get(navigate_url)
        self.driver.implicitly_wait(30)

    def tearDown(self):
        self.driver.quit()

    def test_automate_form(self):
        # Enter First Name
        first_name = self.driver.find_element(By.NAME,'firstname')
        first_name.send_keys('Jassi')

        # Enter Last Name
        last_name = self.driver.find_element(By.NAME,'lastname')
        last_name.send_keys('Maurya')

        # Click on Gender Radio button
        gender = self.driver.find_element(By.ID, 'sex-1')
        print(gender.is_selected())
        gender.click()

        # Enter DOB
        dob = self.driver.find_element(By.ID,'datepicker')
        dob.clear()
        dob.send_keys('19 Mar 1990')

        # Select Profession checkbox
        profession = self.driver.find_element(By.ID,'profession-1')
        profession.click()

        # Select Automation tool checkbox
        automation_tool = self.driver.find_element(By.ID,'tool-2')
        automation_tool.click()

        # Click Submit button
        submit_button = self.driver.find_element(By.ID,'submit')
        submit_button.click()

        time.sleep(5)


if __name__=='__main__':
    unittest.main()


Author
Passionately working as an Automation Developer from more than a decade. Let's connect LinkedIn.

Follow Techlistic

YouTube Channel | Facebook Page | Telegram Channel | Quora Space
Feel free to ask queries or share your thoughts in comments or email us.

Comments

  1. Not many people realise that they have the small errors within their website that create such a big impact to the search engines. velonation com

    ReplyDelete
  2. Hey what a brilliant post I have come across and believe me I have been searching out for this similar kind of post for past a week and hardly came across this. Thank you very much and will look for more postings from you Best python list append service provider.

    ReplyDelete
  3. A very delightful article and videos that you have shared here.Best Selenium Tutorial On Youtube Your blog is a valuable and engaging article for us, and also I will share it with my companions who need this info. Thankful to you for sharing an article and videos like this.

    ReplyDelete
  4. It's very nice of you to share your knowledge through posts. I love to read stories about your experiences. They're very useful and interesting. I am excited to read the next posts. I'm so grateful for all that you've done. Keep plugging. Many viewers like me fancy your writing. Thank you for sharing precious information with us. Best python list append service provider.

    ReplyDelete
  5. I always check this type of advisory post and I found your article which is related to my interest.Online Tutorials For Python This is a great way to increase knowledge for us. Thanks for sharing an article like this.

    ReplyDelete

Post a Comment

Popular posts from this blog

10+ Best Demo Websites for Selenium Automation Testing Practice

Automate Amazon like E-Commerce Website with Selenium WebDriver

How to Automate Google Search with Selenium WebDriver

Handle Static and Dynamic Web Table in Selenium WebDriver

25+ Most Important Selenium WebDriver Commands Tutorial

Automate GoDaddy.com Features with Selenium WebDriver

Top 10 Highly Paid Indian Origin CEO's in USA

50+ Most Important Selenium WebDriver Interview Questions and Answers