Selenium Installation

Selenium installation is the first step to learning automation

1. Python Installation

  • Ensure you have Python installed on your system. You can download it from the official Python website.

  • Verify the installation by running the following command in your terminal or command prompt.
    python –version
  • If it returns the version number, Python is installed.

2. Install Selenium

  • Open a terminal or command prompt and use the following pip command to install Selenium.

    pip install selenium

3. Run the First Selenium Script

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

# Launch a browser
driver = webdriver.Chrome()

# maximize browser window
driver.maximize_window()

#  set implicit wait for 20 sec.
driver.implicitly_wait(20)

# open a facebook URL in the browser
driver.get("https://www.facebook.com")

# send username to field
driver.find_element(By.NAME, "email").send_keys("TestAdmin")

# send password to passwordfield
driver.find_element(By.NAME, "pass").send_keys("Admin@12345")

# click on login button
driver.find_element(By.NAME, "login").click()

# close current browser
driver.close()

Execute script with Firefox

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

# Launch a Firefox browser
driver = webdriver.Chrome()

# maximize browser window
driver.maximize_window()

#  set implicit wait for 20 sec.
driver.implicitly_wait(20)

# open a facebook URL in the browser
driver.get("https://www.facebook.com")

# send username to email field
driver.find_element(By.NAME, "email").send_keys("TestAdmin")

# send password to password field
driver.find_element(By.NAME, "pass").send_keys("Admin@12345")

# click on to login button
driver.find_element(By.NAME, "login").click()

# close current browser
driver.close()


Python Selenium Tutorials

Python selenium tutorials contain all the topics related to selenium and methods belonging to browser action to automate any website.

Selenium is an open-source automation tool primarily used for automating web browsers. It allows developers and testers to simulate user interactions with web applications, making it highly valuable for testing and automating tasks on websites. Selenium supports multiple programming languages, platforms, and browsers.

Key Features and Functionality of Selenium:

1. Cross-Browser Testing:

Selenium supports multiple browsers like:

  • Google Chrome
  • Mozilla Firefox
  • Safari
  • Microsoft Edge
  • Internet Explorer

This allows automation scripts to be executed across different browser environments, ensuring consistent functionality across platforms.

2. Multi-Language Support:

Selenium supports various programming languages, making it flexible for different development environments:

  • Java
  • Python
  • C#
  • Ruby
  • JavaScript (Node.js)
  • PHP

Users can write test scripts in their preferred language.

3. Support for Different Operating Systems:

Selenium can be used on multiple operating systems:

  • Windows
  • macOS
  • Linux

This provides great flexibility to the tester to run tests on different platforms.

4. WebDriver:

Selenium WebDriver is the core component of the Selenium suite. It provides a programming interface to interact with web elements and simulate user actions like clicking, typing, navigating, etc. It interacts directly with the browser without requiring a middle-man, which ensures faster execution and more accurate testing.

5. Multiple Browser Tabs and Windows Support:

Selenium WebDriver can handle switching between multiple browser windows or tabs, helping in simulating real-world test cases like working with pop-ups, new windows, or new tabs.

6. Locating Web Elements:

Selenium offers various ways to locate web elements on a page using locators such as:

  • ID
  • Name
  • Class Name
  • XPath
  • CSS Selectors
  • Tag Name
  • Link Text These locators are used to interact with specific elements like buttons, text boxes, and links.

7. Headless Browser Testing:

Selenium supports headless testing, allowing tests to be run in the background without opening a visible browser. This can improve execution speed, especially when running tests on servers.

8. Selenium Grid:

Selenium Grid allows parallel execution of tests across different machines and browsers. It helps in reducing test execution time by distributing tests across multiple nodes.

9. Automation of Dynamic Web Applications:

Selenium can handle dynamic web pages where elements may change without refreshing the page. This is crucial for testing modern web applications that use technologies like AJAX.

10. Integration with Test Frameworks:

Selenium can be integrated with various test frameworks like:

  • TestNG (Java)
  • JUnit (Java)
  • PyTest (Python)
  • NUnit (C#)

These integrations provide powerful features for assertion, test reporting, and grouping test cases.

11. Handling Alerts and Frames:

Selenium provides functionality to handle browser alerts (pop-ups), and work with iFrames (inline frames) within web pages. This is essential for testing interactions with these web elements.

12. Custom Waits:

Selenium offers both implicit and explicit waits, ensuring the web elements are properly loaded before interacting with them. This helps in making the tests more stable and robust, especially when dealing with slow-loading elements.

13. Data-Driven Testing:

Selenium can be integrated with external data sources like Excel, CSV, or databases, allowing testers to implement data-driven testing. This allows the same test script to run with multiple sets of data, improving test coverage.

14. Record and Playback (Selenium IDE):

Selenium IDE is a simple tool that allows users to record browser actions and generate test scripts automatically. While not as powerful as Selenium WebDriver, it’s useful for quick and simple automation or learning.

15. Open Source and Community Support:

Selenium is free to use and has an active community of developers. It is frequently updated, with a wide range of plugins and libraries available for enhancing its capabilities.

Use Cases of Selenium:

  • Web Application Testing: Automating test cases for web applications across browsers.
  • Regression Testing: Running repeated test cases with Selenium scripts to check for regressions in software behavior.
  • Load Testing: Automating simulations of multiple users interacting with a website.
  • Scraping Data: Extracting data from web pages by automating interactions.

Program to get the median of list elements

In this program, we will get the median of all the elements from the list.

Steps to solve the program
  1. Take an input list with some values.
  2. Sort list items with the sorted() function.
  3. Get the length of the sorted list.
  4. If the length of the list is an even number then the median of the list will average two mid-values of the list.
  5. If the length of a list is odd then the mid-value of the list will be
    the median value.
				
					input_lst = [4, 45, 23, 21, 22, 12, 2]

# sort all list values
sorted_lst = sorted(input_lst)

# get length of sorted list
n = len(sorted_lst)

if n%2 == 0:
    # get first mid value
    mid1 = sorted_lst[n//2]
    # get second mid value
    mid2 = sorted_lst[n//2 -1]
    # average of mid1 and mid2 will be median value
    median = (mid1 + mid2)/2
    print("Median of given list :", median)
else:
    median = sorted_lst[n//2]
    print("Median of given list :",  median)
				
			

Output :

				
					# input_lst = [4, 45, 23, 21, 22, 12, 2]

Median of given list : 21.5
				
			

Related Articles

Python Features and Its Contribution

Python, a popular high-level programming language,
has gained immense popularity over the years due to its simplicity, versatility, and extensive range of features. It has emerged as a go-to language for developers, data scientists, and AI enthusiasts. In this article, we will explore the various features of Python and its significant contributions to the world of programming.

Table of Contents

  1. Introduction to Python
  2. Readability and Simplicity
  3. Interpreted Language
  4. Dynamic Typing
  5. Object-Oriented Programming (OOP)
  6. Extensive Standard Library
  7. Cross-Platform Compatibility
  8. Easy Integration with Other Languages
  9. Large Community and Active Support
  10. Web Development with Python
  11. Data Science and Machine Learning
  12. Automation and Scripting
  13. Testing and Debugging
  14. Scalability and Performance
  15. Conclusion

Introduction to Python

Python, created by Guido van Rossum in the late 1980s, is a versatile and powerful programming language. It was designed with a focus on simplicity and readability, allowing developers to write clean and expressive code. Python follows an open-source philosophy, making it freely available for everyone to use and contribute to its development.

Readability and Simplicity

One of the remarkable features of Python is its emphasis on readability. Its syntax is clear, concise, and easy to understand, making it an ideal language for beginners. Python utilizes indentation to define code blocks, which enhances code readability and enforces good coding practices.

Interpreted Language

Python is an interpreted language, meaning that there is no need for compilation before execution. This feature enables developers to write code and immediately see the results, making the development process faster and more efficient.

Dynamic Typing

In Python, variables are dynamically typed, which means that the type of a variable is determined at runtime. This flexibility allows for more expressive coding and makes Python suitable for rapid prototyping and quick development cycles.

Object-Oriented Programming (OOP)

Python fully supports object-oriented programming, allowing developers to create reusable and modular code. It provides features like classes, objects, inheritance, and polymorphism, making it easy to build complex applications and maintain codebases efficiently.

Extensive Standard Library

Python comes with a vast standard library that provides a wide range of modules and functions for various purposes. This library eliminates the need to write code from scratch for common tasks, such as file handling, network programming, regular expressions, and more. The availability of these modules boosts productivity and speeds up the development process.

Cross-Platform Compatibility

Python is highly portable and can run on different operating systems, including Windows, macOS, Linux, and Unix. Developers can write code once and run it anywhere, making Python an excellent choice for cross-platform development.

Easy Integration with Other Languages

Python’s versatility extends to its ability to integrate with other programming languages seamlessly. It provides robust support for integrating code written in languages like C, C++, and Java, enabling developers to leverage existing codebases and libraries.

Large Community and Active Support

Python boasts a vibrant and active community of developers, who contribute to its growth and share their knowledge and expertise. The availability of extensive documentation, tutorials, and online forums ensures that developers can find answers to their questions and receive support promptly.

Web Development with Python

Python offers various frameworks, such as Django and Flask, that simplify web development tasks. These frameworks provide tools and libraries for handling web requests, managing databases.

creating interactive web applications. With Python, developers can build robust and scalable web solutions, ranging from simple websites to complex web applications.

Data Science and Machine Learning

Python has emerged as a dominant language in the field of data science and machine learning. Its rich ecosystem of libraries and frameworks, including NumPy, Pandas, and scikit-learn, provide powerful tools for data manipulation, analysis, and modeling. Python’s simplicity and ease of use make it an ideal choice for data scientists and machine learning practitioners to explore and analyze data, build predictive models, and deploy machine learning algorithms in real-world applications.

Automation and Scripting

Python excels in automation and scripting tasks. Its concise syntax and extensive library support allow developers to automate repetitive tasks, streamline workflows, and enhance productivity. Whether it’s automating file operations, performing system administration tasks, or building custom scripts, Python provides a versatile and efficient solution.

Testing and Debugging

Python offers robust testing and debugging capabilities, making it easier for developers to ensure the quality and reliability of their code. The built-in unit testing framework, along with third-party libraries like PyTest, simplifies the process of writing and executing tests. Python’s debugging tools, such as pdb and integrated development environments (IDEs) like PyCharm, facilitate efficient debugging and troubleshooting.

Scalability and Performance

While Python is renowned for its simplicity and ease of use, it also provides ways to improve performance and scalability. Integrating Python with high-performance libraries like NumPy and utilizing techniques such as code optimization and parallel processing can significantly enhance the execution speed of Python programs. Additionally, Python’s integration with languages like C and its support for multiprocessing enable developers to tackle computationally intensive tasks efficiently.

Conclusion

Python’s extensive range of features and its contributions to various domains have made it a preferred language for developers worldwide. Its simplicity, readability, and versatility, combined with its vast ecosystem of libraries and frameworks, empower developers to build robust applications, analyze data, automate tasks, and create innovative solutions. Whether you are a beginner or an experienced developer, Python offers a rich and rewarding programming experience.

FAQs (Frequently Asked Questions)

  1. Q: Is Python a beginner-friendly language? A: Yes, Python is known for its simplicity and readability, making it an excellent choice for beginners.
  2. Q: Can Python be used for web development? A: Absolutely! Python offers powerful web development frameworks like Django and Flask for building web applications.
  3. Q: What makes Python suitable for data science? A: Python’s extensive libraries, such as NumPy and Pandas, provide robust tools for data manipulation, analysis, and modeling.
  4. Q: Does Python support object-oriented programming? A: Yes, Python fully supports object-oriented programming, enabling developers to create reusable and modular code.
  5. Q: How can I contribute to the Python community? A: You can contribute to the Python community by participating in open-source projects, sharing your knowledge through tutorials or blog posts, and actively engaging in online forums and communities.
 

Python MCQ Questions (Multiple Choice Quizz)

Python OOPS Programs, Exercises

Python OOPS Programs help beginners to get expertise in Object-Oriented Programming (OOP). Python programming paradigm that focuses on creating objects that encapsulate data and behavior. Python is an object-oriented programming language, which means it supports OOP concepts such as inheritance, polymorphism, encapsulation, and abstraction.

Python OOPS Programs for Practice

1). Python oops program to create a class with the constructor.

2). Python oops program to create a class with an instance variable.

3). Python oops program to create a class with Instance methods.

4). Python oops program to create a class with class variables.

5). Python oops program to create a class with a static method.

6). Python oops program to create a class with the class method.

7). Write a Python Class to get the class name and module name.

8) Write a Python Class object under syntax if __name__ == ‘__main__’.

9). Python class with Single Inheritance.

10). Python Class with Multiple Inheritance.

11). Python Class with Multilevel Inheritance.

12). Python Class with Hierarchical Inheritance.

13). Python Class with Method Overloading.

14). Python Class with Method Overriding.

15). Write a Python Class Program with an Abstract method.

16). Write a Python Class program to create a class with data hiding.

17). Python Class Structure for School Management System.

18). Write a Python Class Structure for Employee Management Application.

19). Write a Python Class with @property decorator.

20). Write a Python Class structure with module-level Import.

21). Create 5 different Python Classes and access them via a single class object.

22). Create 5 Python classes and set up multilevel inheritance among all the classes.

23). Set Instance variable data with setattr and getattr methods.

24). Python oops program with encapsulation.

25). Create a Python class called Rectangle with attributes length and width. Include methods to calculate the area and perimeter of the rectangle.

26). Create a Python class called Circle with attributes radius.
Include methods to calculate the area and circumference of the circle.

27). Create a Python class called Person with attributes name and age. Include a method to print the person’s name and age.

28). Create a Python class called Student that inherits from the Person class.
Add attributes student_id and grades. Include a method to print the student’s name, age, and student ID.

29). Create a Python class called Cat that inherits from the Animal class.
Add attributes breed and weight. Include a method to print the cat’s name, color, breed, and weight.

30). Create a Python class called BankAccount with attributes account_number and balance. Include methods to deposit and withdraw money from the account.

31). Create a Python class called SavingsAccount that inherits from the BankAccount class. Add attributes interest_rate and minimum_balance. Include a method to calculate the interest on the account.

32). Create a Python class called CheckingAccount that inherits from the BankAccount class. Add attributes transaction_limit and transaction_fee. Include a method to check if a transaction is within the limit and deduct the fee if necessary.

33). Create a Python class called Car with attributes make, model, and year.
Include a method to print the car’s make, model, and year.

34). Create a Python class called ElectricCar that inherits from the Car class.
Add attributes battery_size and range_per_charge. Include a method to calculate the car’s range.

35). Create a Python class called StudentRecord with attributes name, age, and grades. Include methods to calculate the average grade and print the student’s name, age, and average grade.

36). Create a Python class called Course with attributes name, teacher, and students. Include methods to add and remove students from the course and print the course’s name, teacher, and list of students.

37). Create a Python class called Shape with a method to calculate the area of the shape. Create subclasses called Square and Triangle with methods to calculate their respective areas.

38). Create a Python class called Employee with attributes name and salary.
Include a method to print the employee’s name and salary.

39). Create a Python class called Manager that inherits from the Employee class.
Add attributes department and bonus. Include a method to calculate the manager’s total compensation.

40). Create a Python class called Customer with attributes name and balance.
Include methods to deposit and withdraw money from the customer’s account.

41). Create a Python class called VIPCustomer that inherits from the Customer class. Add attributes credit_limit and discount_rate. Include a method to calculate the customer’s available credit.

42). Create a Python class called Phone with attributes brand, model, and storage.  Include methods to make a call, send a text message, and check storage capacity.

43). Create a Python class called Laptop with attributes brand, model, and storage. Include methods to start up the laptop, shut down the laptop, and check storage capacity.

44). Create a Python class called Book with attributes title, author, and pages.
Include methods to get the book’s title, author, and number of pages.

45). Create a Python class called EBook that inherits from the Book class.
Add attributes file_size and format. Include methods to open and close the book.

46). Create a Python class called ShoppingCart with attributes items and total_cost. Include methods to add and remove items from the cart and calculate the total cost.

47). Create a Python class called Animal with attributes name and color.
Include a method to print the animal’s name and color.

48). Create a Python class called Dog that inherits from the Animal class.
Add attributes breed and weight. Include a method to print the dog’s name, color, breed, and weight.

Python program to find cartesian product of two sets.

Cartesian product of two sets, Let’s consider we have setA = {3, 5} and setB = {6, 7} then the Cartesian product of two sets will be {(3, 6), (3, 7), (5, 6), (5, 7)}

Cartesian product of two sets with Python

Steps to solve the program

1. Initiate two sets setA and setB.
2. Initiate a result set where we will add the combined value of setA and setB.
3. Apply a nested loop, the first loop will pick the value of setA and the second loop will value of setB.
4. Combine setA and setB values in the tuple and add them to the result set. 
5. Print result set.

				
					# initiate two sets setA and setB
setA = {1, 3}
setB = {2, 6, 7}
result = set()
# use nested loop to interate over setA and setB elements
for val1 in setA:
    for val2 in setB:
        # add combination setA value and setB value to result.
        result.add((val1, val2))
# print output
print(result)

				
			

Output :  Cartesian product of two sets values.

				
					{(1, 2), (3, 7), (1, 7), (3, 6), (1, 6), (3, 2)}
				
			

Related Articles

create two sets of books and find the intersection of sets.

Python Set Programs, Exercises

Python set programs and exercises help beginners to get expertise in set data type, set is a collection of unique data enclosed with ‘{}’ curly braces. User can store only immutable data type to the set. e.g (int, float, string, tuple), mutable data type is not allowed as set element. e.g.  (list, dictionary, set), Let’s consider if we want to store student data, with unique id, then we can use set data type to store the data.

1). Python program to create a set with some elements.

2). Python program to add an element to a set.

3). Python program to remove an element from a set.

4). Python program to find the length of a set.

5). Python program to check if an element is present in a set.

6). Python program to find the union of two sets.

7). Python program to find the intersection of two sets.

8). Python program to find the difference of two sets.

9). Python program to find the symmetric difference of two sets.

10). Python program to show if one set is a subset of another set.

11). Python program to check if two sets are disjoint.

12). Python program to convert a list to a set.

13). Python program to convert a set to a list.

14). Python program to find the maximum element in a set.

15). Python program to find the minimum element in a set.

16). Python program to find the sum of elements in a set.

17). Python program to find the average of elements in a set.

18). Python program to check if all elements in a set are even.

19). Python program to check if all elements in a set are odd.

20). Python program to check if all elements in a set are prime.

21). Python program to check if a set is a proper subset of another set.

22). Python program to find the cartesian product of two sets.

23). Python program to find the power set of a set.

24). Python program to remove all elements from a set.

25). Python program to remove a random element from a set.

26). Python program to find the difference between two sets using the “-” operator.

27). Python program to find the intersection between two sets using the “&” operator.

28). Python program to find the union of multiple sets using the | operator.

29). Python program to find the symmetric difference of two sets using the “^” operator

30). Python program to check if a set is a superset of another set.

31). Python program to find the common elements between two sets.

32). Python program to remove a specific element from a set.

33). Python program to add multiple elements to a set.

34). Python program to remove multiple elements from a set.

35). Python program to check if a set is empty.

36). Python program to check if two sets are equal.

37). Python program to check if a set is a frozen set.

38). Python program to create a frozen set.

39). Python program to find the difference between multiple sets.

40). Python program to find the intersection between multiple sets.

41). Python program to check if any element in a set is a substring of a given string.

42). Python program to check if any element in a set is a prefix of a given string.

43). Python program to check if any element in a set is a suffix of a given string.

44). Python program to find the index of an element in a set.

45). Python program to convert a set to a dictionary with each element as key and value to an empty set.

46). Python program to create a set of even numbers from 1 to 20.

47). Python program to create a set of odd numbers from 1 to 20.

48). Python program to create a set of your favorite actors.

49). Python program to create a set of your favorite movies.

50). Python program to create two sets of books and find the intersection of sets.

51). Python program to find the longest word in a set.

Sort Lines of File with Python

Sort lines of file with Python is an easy way to arrange the file content in ascending order. In this article, we will focus to sort lines of file with the length of each line and sorting the lines in Alphabetical order.

Sort lines of file with line length size:

Let’s consider a text with the name sortcontent.txt which
contains some lines that we will try to sort on the basis of length of the each line.
				
					# sortcontent.txt
This is Python
Hello Good Morning How Are You.
This is Java
Python is good language

				
			
Steps to solve the program
  1. Open the first file using open(“sortcontent.txt”,”r”).
  2. Read all the lines of the file using readlines() method
  3. Now compare all lines one by one and exchange place
    of long length lines with small length lines to re-arrange them
    in ascending order using a nested loop.
  4. re-write all the lines of the list in ascending order.
				
					# Open file in read mode with context manager
with open("sortcontent.txt", "r") as file:
    # Read list of lines.
    FileLines = file.readlines()
    # Initial for loop to start picking each line one by one
    for i in range(len(FileLines)):
        # Initial for loop to compare all remaining line with previous one.
        for j in range(i+1, len(FileLines)):
            # compare each line length, swap small len line with long len line.
            if len(FileLines[i]) > len(FileLines[j]):
                temp = FileLines[i]
                FileLines[i] = FileLines[j]
                FileLines[j] = temp
            else:
                continue

# re-write all the line one by one to the file
with open('ReadContent.txt', "w") as file:
    # Combine all the sequentially arrange lines with join method.
    all_lines = ''.join(FileLines)
    # overwrite all the existing lines with new one
    file.write(all_lines)
				
			

Output: Open the sortcontent.txt file to see the output. below content will be available in the file. All lines of the file will arrange in ascending as per their length.

				
					This is Java
This is Python
Python is good language
Hello Good Morning How Are You.
				
			


Sort lines of file in Alphabetical order
:

Let’s consider a text file with a city name list, where names are mentioned one name in each line In the below program will sort the line of the file in alphabetical order, reads all the names from a file, and print them in alphabetical order.

				
					# cityname.txt
Kolkata
Mumbai
Pune
Bangalore
Delhi
				
			
				
					# open file with context manager
with open('cityname.txt') as file:
    # read all lines with readlines() method.
    file_lines = file.readlines()
    # sort line of file in alphabetical order
    file_lines.sort()
    # print all sorted name using loop
    for line in file_lines:
        print(line)
				
			

When we will run above program, will get following output.

				
					Bangalore
Delhi
Kolkata
Mumbai
Pune
				
			

Related Articles

display words from a file that has less than 5 characters.

Python Projects For Beginners

This article has common Python Projects for beginners, which have all categories of projects from basic to advanced.

Basic Level Projects:

  • Basic Calculator
  • Show Calendar
  • Convert pdf to text
  • Convert image to pdf
  • Convert dictionary to JSON
  • Convert JPEG to PNG
  • Convert JSON to CSV
  • Convert XML to JSON
  • Convert book into audiobook 
  • Decimal to binary convertor and vice versa
  • DNS Records
  • Encrypt and decrypt text
  • Extract zip files
  • Fetch HTTP status code
  • Fetch open ports
  • Hashing passwords
  • Merge csv
  • Merge pdf
  • QR code generator
  • Random password generator

Intermediate Level Projects:

  • Capture screenshot
  • Calculate age
  • Chrome Automation
  • Convert numbers into words
  • Script to encrypt files and folders
  • Article Downloader
  • Duplicate file remover
  • Email GUI
  • Email verification
  • Facebook dp downloader
  • Get wifi password
  • Github repo automation
  • Image to speech
  • Language Translator
  • Password manager
  • Plagiarism checker
  • Python image compressor
  • Send an email with a python
  • Send mail from CSV
  • Set alarm
  • URL shortener

Advance Level Projects:

  • Auto birthday wisher.
  • Auto Backup.
  • Auto-fill the google form.
  • Automate Facebook bot.
  • Automatic certificate generator.
  • Automatic Facebook login
  • Calculator GUI
  • Calendar GUI
  • CLI todo
  • Simple Stopwatch
  • Dictionary GUI
  • Easy cartoonify the image
  • Video Player
  • Extract text from PDF
  • Gesture control media player
  • Google meeting bot
  • Image to sketch
  • Noise reduction script
  • Password manager GUI
  • PDF reader with voice
  • Quote scraper
  • Screen recorder
  • Speech to text
  • Text to speech
  • Text editor
  • Voice Translator
  • Video to audio converter