A Winter Training Report On Automation Using Python
A Winter Training Report On Automation Using Python
On
Automation using Python
Submitted by :
Sandeep yadav
00496502818
ECE 6E Under the Guidance of
Mr. Al Sweigart
Acknowledgement
Next, I would thank Microsoft for developing such a wonderful tool like MS
Word. It helped my work a lot to remain error-free.
Last but clearly not the least, I would thank The Almighty for giving me
strength to complete my report on time.
Preface
I have made this report file on the topic Automation using Python ; I
have tried my best to elucidate all the relevant detail to the topic to be
included in the report. While in the beginning I have tried to give a general
view about this topic.
Introduction to Python
History of Python
Why Python ?
Characteristics of Python
Regular Expressions
Debugging in Python
GUI Automation
Conclusion
INTRODUCTION TO PYTHON
Python is a programming language that lets you work quickly and integrate
systems more efficiently.
There are two major Python versions: Python 2 and Python 3. Both are quite
different.
History of Python
Van Rossum picked the name Python for the new language from a
TV show, Monty Python's Flying Circus.
Why Python ?
The language's core philosophy is summarized in the document The Zen of
Python (PEP 20), which includes aphorisms such as…
Dictionary-
Lists are sequences but the dictionaries are mappings.
They are mappings between a unique key and a value pair.
These mappings may not retain order.
Constructing a dictionary.
Accessing object from a dictionary.
Nesting Dictionaries.
Basic Dictionary Methods.
Basic Syntax
o d={} empty dictionary will be generated and assign keys and values to
it, like d[‘animal’] = ‘Dog’
o d = {'K1':'V1', 'K2’:’V2'}
o d['K1'] outputs 'V1‘
Tuples-
Immutable in nature, i.e they cannot be changed.
No type restriction
Indexing and slicing, everything's same like that in strings and lists.
Constructing tuples.
Basic tuple methods.
Immutability.
When to use tuples?
We can use tuples to present things that shouldn’t change, such as days
of the week, or dates on a calendar, etc.
Sets-
A set contains unique and unordered elements and we can construct them
by using a set() function.
Convert a list into Set-
l=[1,2,3,4,1,1,2,3,6,7]
k = set(l)
k becomes {1,2,3,4,6,7}
Basic Syntax-
x=set()
x.add(1)
x = {1}
x.add(1)
This would make no change in x now
Regular expression in Python
RegEx Module
Python has a built-in package called re, which can be used to work with Regular Expressions.
Import the re module:
import re
RegEx Functions
The re module offers a set of functions that allows us to search a string for a match:
Function Description
Metacharacters
Metacharacters are characters with a special meaning:
| Either or "falls|stays"
Sets
A set is a set of characters inside a pair of square brackets [] with a special meaning:
Set Description
[arn] Returns a match where one of the specified characters (a, r, or n) are present
[a-n] Returns a match for any lower case character, alphabetically
between a and n
[0123] Returns a match where any of the specified digits (0, 1, 2, or 3) are present
We use open () function in Python to open a file in read or write mode. As explained
above, open ( ) will return a file object. To return a file object we use open ()
function along with two arguments, that accepts file name and the mode, whether
to read or write. So, the syntax being: open(filename, mode). There are three kinds
of mode, that Python provides and how files can be opened:
• “ r “, for reading.
• “ w “, for writing.
• “ a “, for appending.
• “ r+ “, for both reading and writing
It read the words from 101.txt file and print the all words which are present in
the file and also tell that word occurring howmany times.
Debugging in Python
pdb — The Python Debugger
The debugger’s prompt is (Pdb). Typical usage to run a program under control of
the debugger is:
Debugger Commands
The commands recognized by the debugger are listed below. Most commands can
be abbreviated to one or two letters as indicated; e.g. h(elp) means that
either h or help can be used to enter the help command (but not he or hel,
nor H or Help or HELP). Arguments to commands must be separated by
whitespace (spaces or tabs). Optional arguments are enclosed in square brackets
([]) in the command syntax; the square brackets must not be typed. Alternatives in
the command syntax are separated by a vertical bar (|).
h(elp) [command]
Without argument, print the list of available commands. With a command as
argument, print help about that command. help pdb displays the full documentation
(the docstring of the pdb module). Since the command argument must be an
identifier, help exec must be entered to get help on the ! command.
w(here)
Print a stack trace, with the most recent frame at the bottom. An arrow indicates
the current frame, which determines the context of most commands.
d(own) [count]
Move the current frame count (default one) levels down in the stack trace (to a
newer frame).
u(p) [count]
Move the current frame count (default one) levels up in the stack trace (to an older
frame).
disable [bpnumber ...]
Disable the breakpoints given as a space separated list of breakpoint numbers.
Disabling a breakpoint means it cannot cause the program to stop execution, but
unlike clearing a breakpoint, it remains in the list of breakpoints and can be
(re-)enabled.
enable [bpnumber ...]
Enable the breakpoints specified.
ignore bpnumber [count]
Set the ignore count for the given breakpoint number. If count is omitted, the
ignore count is set to 0. A breakpoint becomes active when the ignore count is
zero. When non-zero, the count is decremented each time the breakpoint is reached
and the breakpoint is not disabled and any associated condition evaluates to true.
commands [bpnumber]
Specify a list of commands for breakpoint number bpnumber. The commands
themselves appear on the following lines.
s(tep)
Execute the current line, stop at the first possible occasion (either in a function that
is called or on the next line in the current function).
n(ext)
Continue execution until the next line in the current function is reached or it
returns. (The difference between next and step is that step stops inside a called
function, while next executes called functions at (nearly) full speed, only stopping
at the next line in the current function.)
unt(il) [lineno]
Without argument, continue execution until the line with a number greater than the
current one is reached.
With a line number, continue execution until a line with a number greater or equal
to that is reached. In both cases, also stop when the current frame returns.
r(eturn)
Continue execution until the current function returns.
c(ont(inue))
Continue execution, only stop when a breakpoint is encountered.
j(ump) lineno
Set the next line that will be executed. Only available in the bottom-most frame.
This lets you jump back and execute code again, or jump forward to skip code that
you don’t want to run.
It should be noted that not all jumps are allowed – for instance it is not possible to
jump into the middle of a for loop or out of a finally clause.
Web Scrapping using Beautiful Soup
Steps involved in web scraping:
• Send an HTTP request to the URL of the webpage you want to access. The
server responds to the request by returning the HTML content of the webpage. For
this task, we will use a third-party HTTP library for python-requests.
• Once we have accessed the HTML content, we are left with the task of parsing
the data. Since most of the HTML data is nested, we cannot extract data simply
through string processing. One needs a parser which can create a nested/tree
structure of the HTML data. There are many HTML parser libraries available but
the most advanced one is html5lib.
• Now, all we need to do is navigating and searching the parse tree that we
created, i.e. tree traversal. For this task, we will be using another third-party
python library, Beautiful Soup. It is a Python library for pulling data out of HTML
and XML files.
import requests
URL = "https://www.automatetheboringstuffusingpython.org/"
r = requests.get(URL)
print(r.content)
A really nice thing about the BeautifulSoup library is that it is built on the top of
the HTML parsing libraries like html5lib, lxml, html.parser, etc. So
BeautifulSoup object and specify the parser library can be created at the same
time.
In the example above,
soup = BeautifulSoup(r.content, 'html5lib')
We create a BeautifulSoup object by passing two arguments:
r.content : It is the raw HTML content.
html5lib : Specifying the HTML parser we want to use.
import requests
from bs4 import BeautifulSoup
import csv
URL = "http://www.values.com/inspirational-quotes"
r = requests.get(URL)
soup = BeautifulSoup(r.content, 'html5lib')
quotes=[] # a list to store quotes
table = soup.find('div', attrs = {'id':'all_quotes'})
for row in table.findAll('div',
attrs = {'class':'col-6 col-lg-3 text-center margin-30px-bottom sm-margin-30px-top'}):
quote = {}
quote['theme'] = row.h5.text
quote['url'] = row.a['href']
quote['img'] = row.img['src']
quote['lines'] = row.img['alt'].split(" #")[0]
quote['author'] = row.img['alt'].split(" #")[1]
quotes.append(quote)
filename = 'inspirational_quotes.csv'
with open(filename, 'w', newline='') as f:
w = csv.DictWriter(f,['theme','url','img','lines','author'])
w.writeheader()
for quote in quotes:
w.writerow(quote)
Now, in the table element, one can notice that each quote is inside a div container
whose class is quote. So, we iterate through each div container whose class is
quote.
Here, we use findAll() method which is similar to find method in terms of
arguments but it returns a list of all matching elements. Each quote is now iterated
using a variable called row.
Here is one sample row HTML content for better understanding:
Email
Simple Mail Transfer Protocol (SMTP) is a protocol, which handles sending e-
mail and routing e-mail between mail servers.
Python provides smtplib module, which defines an SMTP client session object
that can be used to send mail to any Internet machine with an SMTP or ESMTP
listener daemon.
Here is a simple syntax to create one SMTP object, which can later be used to
send an e-mail −
import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
Here is the detail of the parameters −
host − This is the host running your SMTP server. You can specify IP address
of the host or a domain name like tutorialspoint.com. This is optional
argument.
port − If you are providing host argument, then you need to specify a port,
where SMTP server is listening. Usually this port would be 25.
local_hostname − If your SMTP server is running on your local machine, then
you can specify just localhost as of this option.
An SMTP object has an instance method called sendmail, which is typically used
to do the work of mailing a message. It takes three parameters −
The sender − A string with the address of the sender.
The receivers − A list of strings, one for each recipient.
The message − A message as a string formatted as specified in the various
RFCs.
Python tracks and controls mouse using coordinate system of screen. Suppose the
resolution of your screen is 1023×767, then your screen’s coordinate system looks
like to know your screen resolution, type the following in a text editor:
import pyautogui
print(pyautogui.size())
This python code use size() function to output your screen resolution in x,y format:
This code uses moveTo() function, which takes x and y coordinates, and an optional
duration argument. This function moves your mouse pointer from it’s current
location to x,y coordinate, and takes time as specified by duration argument to do
so.
moveRel() function moves the mouse pointer relative to its previous position. Type:
This code will move mouse pointer at (0, 50) relative to its original position. For
example, if mouse position before running the code was (1000, 1000), then this
code will move the pointer to coordinates (1000, 1050) in duration 1 second.
Getting current mouse position:
use position() function to get current position of the mouse pointer. Type:
print(pyautogui.position())
or wherever your mouse was residing at the time of executing the program.
pyautogui.click(100, 100)
This code performs a typical mouse click at the location (100, 100).
We have two functions associated with drag operation of mouse, dragTo and
dragRel. they perform similar to moveTo and moveRel functions, except they hold
the left mouse button while moving, thus initiating a drag. This functionality can be
used at various places, like moving a dialog box, or drawing something
automatically using pencil tool in MS Paint.
scroll function takes no. of pixels as argument, and scrolls the screen up to given
number of pixels.
pyautogui.scroll(200)
You can automate typing of string by using typewrite() function. just pass the string
which you want to type as argument of this function. Ex:
pyautogui.click(100, 100);pyautogui.typewrite(“hello”)
suppose a text field was present at coordinates 100, 100 on screen, then this code
will click the text field to make it active and type “hello” in it.
You can pass key names separately through typewrite() function. For example:
This code is automatic equivalent of typing “a”, pressing left arrow key, and
pressing left control key.
Use hotkey() function to press combination of keys like ctrl-c, ctrl-a etc. Ex:
pyautogui.hotkey(“ctrlleft”, “a”)
This code is automatic equivalent of pressing left ctrl and “a”simultaneously. Thus
in windows, this will result in selection of all text present on screen.
Conclusions
I believe the trial has shown conclusively that it is both possible and desirable
to use Python as the principal teaching language:
The training program having online for whole 2 weeks. In my opinion. I have
gained lots of knowledge and experience needed to be successful in great
engineering challenge as in my opinion, Engineering is after all a Challenge ,and
not a job .