Eden Marco

If you are reading this, then chances are you have learned some basic Python and want to build your coding skills and get your feet wet with some real-world Python automation projects. Learning simple Python through coding examples is important when you are just beginning, but to truly level up your Python skills, you need to build things, and why not learn to automate real-world tasks?

To help you out, Python offers a variety of libraries you can use in automation projects, as mentioned in the What is Python blog. We can easily tackle real-world problems with Python and automate tasks like operating system navigation, web browsing, social media posting, and much more with the help of these libraries. Here are three quick, fun Python automation ideas to show you how to handle repetitive tasks with Python code.

Get notified when Elon Musk tweets about Tesla

Tweet by Elon Musk, Python automation example
Image Source: https://twitter.com/

In this first Python automation script, we will be listening to Elon Musk’s Twitter account for any tweet he makes about Tesla and print them out. Before you start, you need to make sure you have the Python requests package installed. If not, open a command prompt and enter this on the command line.

pip install requests
Real World Python Test Automation with Pytest (Django app)

Last Updated October 2021

Bestseller
  • 69 lectures
  • Intermediate Level
4.8 (418)

Learn Pytest by building a full Django application with a Continuous Integration system, software testing best practices | By Eden Marco

Explore Course

Now, get an API token from Twitter so we can make requests to their API. Make sure to replace the TWITTER_BEARER_TOKEN variable with your API key. Then simply query Elon Musk’s screen name for tweets and filter only those tweets containing the string ‘tesla’.

import requests
TWITTER_BEARER_TOKEN = 'AAAAAAAAAAAXXXXXXXXAAHXYXXXXXXXXg’

screen_name = 'elonmusk'
response = requests.get(url="https://api.twitter.com/1.1/statuses/user_timeline.json", params={
   "screen_name": screen_name, "count": 1},
                       headers={"Authorization": f"Bearer {TWITTER_BEARER_TOKEN}"})

last_tweets = response.json()
for a tweet in last_tweets:
   if "tesla" in tweet['text'].lower():
       tweet_link = f"https://twitter.com/{screen_name}/status/{tweet['id_str']}"
       tesla_mentioned_message = f"{screen_name} tweeted: \n {tweet['text']} \n LINK: \n {tweet_link}"
       print(tesla_mentioned_message)

Now that you see how this Python code works, why not add some new features? You can add an infinite while loop and make sure each tweet is only printed once by saving the id of the last posted tweet and printing only if there is a new tweet. Or you can send tweets to a dedicated Telegram channel with a Telegram bot.

Master the cookie clicker game with Selenium and Python automation

Gif of cookie clicker game with Python automation

You can also use Python to automate your gameplay so you can get the highest score possible. In this Python automation script, we will automate playing the online Cookie Clicker game using Selenium

Selenium is a tool used to automate web browsers, and software developers can interact with it in multiple programming languages using its API. It is often used to automate website testing in the industry, but you can use it to automate many online tasks, including playing a game faster than humanly possible.

Top courses in Python

Programming Numerical Methods in Python
Murad Elarbi
4.6 (670)
Bestseller
Python Network Programming for Network Engineers (Python 3)
David Bombal, Experts with David Bombal
4.7 (7,628)
Python for Data Science and Machine Learning Bootcamp
Jose Portilla
4.7 (116,770)
Bestseller
Machine Learning A-Z™: Hands-On Python & R In Data Science
Kirill Eremenko, Hadelin de Ponteves, Ligency I Team, Ligency Team
4.6 (159,923)
Spark and Python for Big Data with PySpark
Jose Portilla
4.5 (18,779)
Bestseller

More Python Courses

Before starting, you need to make sure you have the Python Selenium package installed. If not, install it with this command.

pip install selenium

Once Selenium is installed, execute this script.

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.action_chains import ActionChains
import time

if __name__ == "__main__":
   service = Service(ChromeDriverManager().install())
   driver = webdriver.Chrome(service=service)
   driver.get("https://orteil.dashnet.org/cookieclicker/")
   time.sleep(5)

   MAX_COOKIE_CLICKS = 50
   big_cookie_element = driver.find_element(value="bigCookie")
   for _ in range(MAX_COOKIE_CLICKS):
       time.sleep(0.01)
       actions = ActionChains(driver)
       actions.click(big_cookie_element)
       actions.perform()

This Python code will open your Chrome browser using Selenium, navigate to the Cookie Clicker game, find the big cookie on the page, and start clicking until you stop the script.

Automatically move files with the OS module and watchdog package

Gif of Python watchdog package, python automation

If your Downloads folder is like mine, it is probably full of random files that aren’t in any specific order. In this automation project, we will write a Python script that will watch your Downloads folder for new files, classify them by their file type, and move them to a directory created specifically for them.

To do this, we will be using the Python watchdog package. This package is designed to monitor a specific folder and notify you when anything changes. Other than that, you don’t need any extra Python libraries. Here is the Python script:

from watchdog.events import FileSystemEventHandler
from watchdog.observers.polling import PollingObserver

import os
import time

watched_directory = "/Users/edenmarco/Downloads"
NEW_DIR = "gifs"


class MyDownloadsHanlder(FileSystemEventHandler):
   def on_modified(self, event):
       for file_name in os.listdir(watched_directory):
           watched_file = f"{watched_directory}/{file_name}"
           new_dest_direcotry = f"{watched_directory}/{NEW_DIR}"

           if not os.path.exists(new_dest_direcotry):
               os.mkdir(new_dest_direcotry)

           if file_name.endswith(".gif"):
               os.rename(watched_file, f"{new_dest_direcotry}/{file_name}")


if __name__ == "__main__":
   event_handler = MyDownloadsHanlder()
   observer = PollingObserver()
   observer.schedule(
       event_handler=event_handler, path=watched_directory, recursive=False
   )
   observer.start()
   while True:
       time.sleep(5)

The Python code above will watch the folder in the watched_directory variable. Whenever a file gets added to it, it will loop through all the files in the directory, check for filenames with the .gif extension, and put them in the gifs folder.

To modify this code to run on your system, you will just have to modify one line of code. Set the watched_directory variable to your Downloads folder file path. Since the script only handles gif files currently, you can also modify it to search for more files, like text files, video files, or PDF documents.

Now that you know how to automate a few tasks in Python, why not try your hand at building more things with Python? After all, the best way to Learn Python is by understanding what Python is used for and then writing code. Udemy has many Python Courses where any level student can begin. Taking a look at How Long Does it Take to Learn Python and 9 Python coding projects by Ziyad Yehia can help you decide what to work on next.

Page Last Updated: February 2022