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 September 2022

Bestseller
  • 70 lectures
  • Intermediate Level
4.7 (767)

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

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

Python for Beginners
Navin Reddy
4.6 (9,459)
Python for Beginners (2023)
AlgoSTEM Inc.
4.4 (3,109)
Python 3: Deep Dive (Part 1 – Functional)
Dr. Fred Baptiste
4.8 (11,671)
Python for Data Analysis & Visualization
Malvik Vaghadia, Pathfinder Analytics
4.6 (1,623)
100 Days of Code: The Complete Python Pro Bootcamp
Dr. Angela Yu, Developer and Lead Instructor
4.7 (321,424)
Bestseller
Learn Python & Ethical Hacking From Scratch
Zaid Sabih, z Security
4.7 (19,788)

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.

Neo4j 2022 Graph DB- Game of Thrones Real world Dataset
Eden Marco | LLM Specialist
4.2 (186)
Real World Python Test Automation with Pytest (Django app)
Eden Marco | LLM Specialist
4.7 (767)
Bestseller
LangChain- Develop LLM powered applications with LangChain
Eden Marco | LLM Specialist
4.6 (17,317)
Bestseller
【한글자막】 랭체인 – LangChain 으로 LLM 기반 애플리케이션 개발하기
Eden Marco | LLM Specialist, 웅진씽크빅 글로벌
4.5 (231)
LlamaIndex Develop LLM powered applications (Legacy)
Eden Marco | LLM Specialist
4.2 (534)
LangGraph- Develop LLM powered agents with LangGraph
Eden Marco | LLM Specialist
4.7 (412)
Bestseller

Courses by Eden Marco | LLM Specialist

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