0% found this document useful (1 vote)
996 views66 pages

Selenium With Python

This document provides an overview of Python programming concepts including: - Python is a widely used programming language that supports object-oriented, imperative, functional and procedural programming. - Key Python features include a large standard library, cross-platform compatibility, and an easy to read syntax. - Common Python data types include strings, integers, floats, booleans, lists, tuples, dictionaries and sets. - Control flow structures like if/else statements and for/while loops are used to control program flow. - Functions allow code reuse and modular programming. Object-oriented concepts like classes, objects, inheritance and encapsulation are supported. - The document discusses Python installation, editors, basic syntax like variables and operators,

Uploaded by

Agus Hari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (1 vote)
996 views66 pages

Selenium With Python

This document provides an overview of Python programming concepts including: - Python is a widely used programming language that supports object-oriented, imperative, functional and procedural programming. - Key Python features include a large standard library, cross-platform compatibility, and an easy to read syntax. - Common Python data types include strings, integers, floats, booleans, lists, tuples, dictionaries and sets. - Control flow structures like if/else statements and for/while loops are used to control program flow. - Functions allow code reuse and modular programming. Object-oriented concepts like classes, objects, inheritance and encapsulation are supported. - The document discusses Python installation, editors, basic syntax like variables and operators,

Uploaded by

Agus Hari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

Web Automation With

Selenium Web Driver And


Python

PT Swamedia Informatika
2019
Material List
• Python Fundamental
• Selenium WebDriver with Python
What is Python
Python is a widely used high-level programming language for
general purpose. Python features a dynamic type system and
automatic memory management and supports multiple
programming paradigms, including object-oriented, imperative,
functional programming, and procedural styles. It has a large and
comprehensive standart library.
What Python can do ?
● Web Development (server-side),
● Software Development,
● Mathematics,
● System Scripting
Why Python ?
● Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
● Python has a simple syntax similar to the English language.
● Python has syntax that allows developers to write programs with fewer lines than
some other programming languages.
● Python runs on an interpreter system, meaning that code can be executed as soon
as it is written. This means that prototyping can be very quick.
● Python can be treated in a procedural way, an object-orientated way or a
functional way.
Current Python Version
● Python 3.x is the current version and is under active
development
● Python 2.x is the legacy version and will receive only security
updates until 2020
Python Installation
Install the current Python version https://www.python.org/downloads/
Python Editor
• IDLE is a simple editor for Python, that comes bundled with
Python
• Online Python shell https://www.python.org/shell/
• Using favorite IDE like Sublime, Visual Studio Code, or
Pycharm
<variable name> = <value> ● # String
● # Integer name = 'John Doe'
a=2 print(name)
print(a) # Output: John Doe
# Output: 2 ● # Boolean
● # Floating point q = True
pi = 3.14 print(q)
print(pi) # Output: True
# Output: 3.14 ● # Empty value or null data type
● # String x = None
c = 'A' print(x)
print(c) # Output: None
# Output: A
Block Indentation in Python
Python uses indentation to define control and loop constructs. This contributes to
Python's readability, however, it requires the programmer to pay close attention to the
use of whitespace.
Python uses the colon symbol ( : ) and indentation for showing where blocks of code
begin and end. That is, blocks in Python, such as functions, loops, if clauses and other
constructs, have no ending identifiers. All blocks start with a colon and then contain the
indented lines below it.
Block Indentation in Python
Casting
Python Strings
● String literals in python are surrounded by either single quotation marks, or double
quotation marks. 'hello' is the same as "hello"
● Strings in Python are arrays of bytes representing unicode characters
● Python does not have a character data type, a single character is simply a string
with a length of 1. Square brackets can be used to access elements of the string.
Python Strings
Get the character at position 1 Substring. Get the characters from
position 2 to position 5
Python Strings
There are a lot of methods that can use string operation
Python allows for command line input.
like :
Below code will ask for your name and
● strip() method to remove whitespace in string
print it into the terminal
character
● len() method to get size of a string
● lower() method to make a return of string to be
lower case
● upper() method to make a return of string to be
upper case
● replace() method to replace a string with another
string
● split() method to split a string into substrings
Python Operator
Operators are used to perform operations on variables and values.
Python divides the operators in the following groups :
● Arithmetic operators
● Assignment operators
● Comparison operators
● Logical operators
● Identity operators
● Membership operators
● Bitwise operators
Python Arithmetic Operators
Arithmetic operators are used with numeric values to perform common mathematical
operations
Python Assignment Operators
Assignment operators are used to assign values to variables
Python Comparator Operators
Comparison operators are used to compare two values :
Python Logical Operators
Logical operators are used to combine conditional statements :
Python Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location :
Python Membership Operators
Membership operators are used to test if a sequence is presented in an object :
Python Bitwise Operators
Bitwise operators are used to compare (binary) numbers :
Python Array (list)
Array is a special variable, which can
hold more than one value at a time.

Accessing Array using arr[index]

Return length of array using len() method


Array Methods
Python has a set of built-in methods that you can use on lists/arrays
Array Methods
Python Tuples
A tuple is a collection which is ordered and unchangeable. In Python tuples are
written with round brackets.
Set
A set is a collection which is unordered and unindexed. In Python sets are written with
curly brackets.
Set Methods
Python has a set of built-in methods that you can use on sets
Set Methods
Set Methods
Dictionary
A dictionary is a collection which is unordered, changeable and indexed. In Python
dictionaries are written with curly brackets, and they have keys and values
Dictionary
Dictionary Methods
Python has a set of built-in methods that you can use on dictionaries
Dictionary Methods
Control Flow (IF - ELSE)
Python supports the usual logical conditions from mathematics:
● Equals: a == b
● Not Equals: a != b
● Less than: a < b
● Less than or equal to: a <= b
● Greater than: a > b
● Greater than or equal to: a >= b
Control Flow (IF - ELSE)
Control Flow With Logical Operator
Python For Loop
A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string). With the for loop we can execute a set of statements,
once for each item in a list, tuple, set etc.
Python While Loop
With the while loop we can execute a set of statements as long as a condition is true
Python Functions
A function is a block of code which only runs when it is called. You can pass data,
known as parameters, into a function. A function can return data as a result.
Python Functions
Object Oriented Programming in Python
Object-oriented programming (OOP) is a programming paradigm based on the concept
of "objects", which can contain data, in the form of fields (often known as attributes),
and code, in the form of procedures (often known as methods).
A feature of objects is an object's procedures that can access and often modify the data
fields of the object with which they are associated (objects have a notion of "this" or
"self").
Inheritance
Inheritance is the mechanism of basing an object or class upon another object
(prototype-based inheritance) or class (class-based inheritance), retaining similar
implementation. Also defined as deriving new classes (sub classes) from existing ones
(super class or base class) and forming them into a hierarchy of classes.
Polymorphism
Polymorphism is the provision of a single interface to entities of different types or the
use of a single symbol to represent multiple different types.
Encapsulation
Encapsulation refers to the bundling of data with the methods that operate on that data.
Encapsulation is used to hide the values or state of a structured data object inside a
class, preventing unauthorized parties' direct access to them.
Python Classes and Objects
A Class is like an object constructor, or a "blueprint" for creating objects.
Python __init__() Function
All classes have a function called __init__(), which is always executed when the class
is being initiated.
Use the __init__() function to assign values to object properties, or other operations
that are necessary to do when the object is being created.
So what the ‘self’ keyword means ?
The self parameter is a reference to the class itself, and is used to access variables that
belongs to the class.
It does not have to be named self , you can call it whatever you like, but it has to be the
first parameter of any function in the class.
Python Inheritance
Inheritance allows us to define a class that inherits all the methods and properties from
another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.
Python Inheritance
Python Inheritance
If you want to customize your child class (e.x. Adding property, adding method, or
overriding parent’s method) you can use __init__() function.
Python Overriding Parent Method
Overriding means that a child class wants to change the implementation of parent class
method.
Python Modules
Consider a module to be the same as a code library.
A file containing a set of functions you want to include in your application.
Python Datetime
A date in Python is not a data type of its own, but we can import a module named
datetime to work with dates as date objects.
Python PIP
PIP is a package manager for Python packages, or modules if you like.
PIP is included if you have python 3.4 version or later.
Visit link https://pypi.org/project/pip/ to install pip.
Visit link https://pypi.org/ to list all python packages.
Python Exception Handling
When an error occurs, or exception as we call it, Python will normally stop and
generate an error message.
The try block lets you test a block of code for errors.
The except block lets you handle the error.
The finally block lets you execute code, regardless of the result of the try- and except
blocks.
Python Exception Handling
What is Selenium ?
Selenium is a set of different software tools each with a different approach to
supporting test automation. Most Selenium QA Engineers focus on the one or two
tools that most meet the needs of their project, however learning all the tools will give
you many different options for approaching different test automation problems. The
entire suite of tools results in a rich set of testing functions specifically geared to the
needs of testing of web applications of all types. These operations are highly flexible,
allowing many options for locating UI elements and comparing expected test results
against actual application behavior. One of Selenium’s key features is the support for
executing one’s tests on multiple browser platforms.
Selenium Web Driver vs Selenium IDE
Selenium WebDriver Selenium IDE
A collection of language specific bindings to drive a will do simple record-and-playback of interactions
browser -- the way it is meant to be driven. with the browser.

● create quick bug reproduction scripts


● create robust, browser-based regression ● create scripts to aid in automation-aided
automation suites and tests exploratory testing
● scale and distribute scripts across many
environments
Selenium WebDriver
Selenium WebDriver was developed to better support dynamic web pages where
elements of a page may change without the page itself being reloaded. WebDriver’s
goal is to supply a well-designed object-oriented API that provides improved support
for modern advanced web-app testing problems.
Unit Testing Framework
Unit testing framework was originally inspired by JUnit and has a similar flavor as
major unit testing frameworks in other languages. It supports test automation, sharing
of setup and shutdown code for tests, aggregation of tests into collections, and
independence of the tests from the reporting framework.
Unit Testing Framework
Unit Testing Framework
Selenium WebDriver Implementation
● Install selenium via pip
● Download driver for specific browser (e.x. ChromeDriver or FirefoxDriver)
Reference
https://www.w3schools.com/python/
https://goalkicker.com/PythonBook/
https://www.seleniumhq.org/
https://docs.python.org/3/library/unittest.html
https://selenium-python.readthedocs.io/getting-started.html

Common questions

Powered by AI

Selenium WebDriver is preferable over Selenium IDE when creating robust, browser-based regression automation suites and tests that need to scale or be distributed across different environments . WebDriver supports executing tests on dynamic web pages where elements may change without reloading, a feature more suitable for advanced web applications . On the other hand, Selenium IDE is more appropriate for quick bug reproduction scripts and simple record-and-playback scenarios . In projects requiring complex interactions and cross-browser testing, WebDriver provides a more sophisticated, object-oriented API that enhances flexibility and control over test behaviors .

Python uses indentation to define code blocks such as functions, loops, and conditional statements instead of using braces or keywords like 'end' . This approach enforces a clean and consistent visual structure, making the code more readable and reducing clutter on the screen. By relying on whitespace, Python encourages developers to write more orderly and clear code, minimizing errors that can arise from incorrect block delimitations present in other languages .

Python's comprehensive standard library significantly enhances its capabilities by providing a wide array of modules and functions that cater to various tasks including string manipulation, file I/O, system calls, and protocol handling . This extensive library reduces the need for external dependencies and facilitates rapid development and prototyping by offering ready-to-use solutions for common programming problems . It supports Python's goal of enabling a more productive programming environment by streamlining workflow and allowing developers to focus on application-specific logic .

Python handles exceptions using the try-except-finally mechanism. The try block tests a block of code for potential errors, while the except block handles the error if one occurs . The finally block is used to execute code regardless of the result, allowing cleanup actions or the release of resources, ensuring that certain code runs no matter what . This structured exception handling model isolates error-prone code segments and helps in differentiating error-handling code from regular code logic .

Python's list comprehensions offer a concise and readable syntax to create new lists by iterating over an existing iterable and potentially applying a filtering condition or transformation to each element . This approach reduces the need for explicit loops and temporary variables, making the code more efficient and clear. For example, to create a list of squares of even numbers from 0 to 10, one could use the comprehension: squares = [x**2 for x in range(11) if x % 2 == 0]. This generates the new list [0, 4, 16, 36, 64, 100], efficiently .

Python supports multiple programming paradigms, including object-oriented, imperative, functional programming, and procedural styles . This flexibility benefits software development by allowing developers to choose the most appropriate paradigm for a particular task, enhancing code clarity, reusability, and maintainability . It also enables the integration of different paradigms within a single project, which can lead to more efficient problem-solving and easier adaptation of new programming techniques .

The '__init__()' function serves as the initializer for Python classes, allowing for the setting of initial values for object attributes and the execution of necessary setup procedures when an object is created . It can be creatively used in object-oriented programming to enforce constraints, validate inputs, or automate complex setup processes, thereby ensuring that objects start in a consistent and valid state . '__init__()' can also be customized to handle parameterized and conditional initializations, providing flexibility in object construction .

Python's PIP is a package manager that greatly enhances the language's extensibility by simplifying the installation and management of external modules . PIP provides developers easy access to an extensive repository of pre-built libraries on PyPI, allowing them to promptly integrate third-party functionalities into their applications. For instance, a developer can enhance a web application by installing the Requests module via PIP, enabling seamless HTTP requests handling in just a few commands, saving time and ensuring compatibility . This streamlines the development process by avoiding the need to manually download and configure packages .

Python's dynamic type system allows variables to be assigned without explicitly declaring their types, fostering flexibility and reducing boilerplate code . This feature benefits developers by promoting rapid prototyping and simplifying program syntax, as the language determines the type at runtime . However, it also introduces challenges such as increased runtime errors due to unexpected type changes and less predictability in large codebases compared to statically typed languages where type consistency is enforced at compile time . Consequently, developers may rely on unit tests and type hinting to mitigate these issues .

Polymorphism in Python’s object-oriented programming allows the same interface to be used for different data types or classes, enhancing code flexibility and integration . This is typically implemented through method overriding or interfaces with abstract classes. For example, having a 'draw()' method in a base class Shape, both Circle and Square classes can override this method to provide their specific implementation of 'draw'. Polymorphism allows these objects to be used interchangeably in a list of Shapes, enabling unified handling . This approach simplifies code maintenance and extension by promoting a uniform interface .

You might also like