DEV Community

Trix Cyrus
Trix Cyrus

Posted on

How to Automate Everyday Tasks with Python (Part 2)

Author: Trix Cyrus

Waymap Pentesting tool: Click Here
TrixSec Github: Click Here

In Part 1, we explored how to use Python to automate file management, web scraping, sending emails, Google Sheets, and system monitoring. In Part 2, we will continue by covering more advanced tasks like automating APIs, scheduling scripts, and integrating automation with third-party services.

7. Automating API Requests

Many web services provide APIs to interact with their platforms programmatically. Using the requests library, you can easily automate tasks like fetching data from APIs, posting updates, or performing CRUD operations on cloud services.

import requests

# OpenWeatherMap API configuration
api_key = 'your_api_key'
city = 'New York'
url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}'

# Send a GET request to fetch weather data
response = requests.get(url)
data = response.json()

# Extract temperature information
temperature = data['main']['temp']
weather = data['weather'][0]['description']

print(f"Temperature: {temperature}°K")
print(f"Weather: {weather}")
Enter fullscreen mode Exit fullscreen mode

This script fetches the current weather data for a specified city from the OpenWeatherMap API and displays it.

8. Scheduling Tasks with Python

Sometimes you need to automate tasks to run at specific times or intervals. Python's schedule library makes it easy to set up jobs that run automatically at certain times.

import schedule
import time

# Task function to be executed
def task():
    print("Executing scheduled task...")

# Schedule the task to run every day at 9 AM
schedule.every().day.at("09:00").do(task)

# Keep the script running to check the schedule
while True:
    schedule.run_pending()
    time.sleep(1)
Enter fullscreen mode Exit fullscreen mode

This script schedules a task to run every day at 9 AM, using a simple scheduling loop to keep the task running.

9. Automating Database Operations

Python can be used to interact with databases, automate data entry, and perform operations like reading, updating, and deleting records. The sqlite3 module allows you to manage SQLite databases, while other libraries (like psycopg2 or MySQLdb) work with PostgreSQL and MySQL.

import sqlite3

# Connect to SQLite database
conn = sqlite3.connect('tasks.db')

# Create a cursor object to execute SQL commands
cur = conn.cursor()

# Create a table for storing tasks
cur.execute('''CREATE TABLE IF NOT EXISTS tasks (id INTEGER PRIMARY KEY, task_name TEXT, status TEXT)''')

# Insert a new task
cur.execute("INSERT INTO tasks (task_name, status) VALUES ('Complete automation script', 'Pending')")

# Commit changes and close the connection
conn.commit()
conn.close()
Enter fullscreen mode Exit fullscreen mode

This script creates an SQLite database, adds a "tasks" table, and inserts a new task into the database.

10. Automating Excel File Management

Python, along with the openpyxl or pandas libraries, can be used to automate reading, writing, and modifying Excel files. This is especially useful for automating data analysis and reporting tasks.

import pandas as pd

# Read Excel file
df = pd.read_excel('data.xlsx')

# Perform some operation on the data
df['Total'] = df['Price'] * df['Quantity']

# Write the modified data back to a new Excel file
df.to_excel('updated_data.xlsx', index=False)
Enter fullscreen mode Exit fullscreen mode

This script reads an Excel file, performs a calculation on the data, and writes the updated data to a new file.

11. Automating Browser Interactions with Selenium

Using Selenium, Python can automate interactions with web browsers such as logging into accounts, filling forms, and performing repetitive web tasks.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

# Set up the browser driver
driver = webdriver.Chrome()

# Open the login page
driver.get('https://example.com/login')

# Locate the username and password fields, fill them in, and log in
username = driver.find_element_by_name('username')
password = driver.find_element_by_name('password')
username.send_keys('your_username')
password.send_keys('your_password')
password.send_keys(Keys.RETURN)

# Close the browser
driver.quit()
Enter fullscreen mode Exit fullscreen mode

This script opens a web browser, navigates to a login page, fills in the credentials, and logs in automatically.

12. Automating Cloud Services

Python integrates well with cloud services like AWS, Google Cloud, and Azure. Using the boto3 library, you can automate tasks like managing S3 buckets, EC2 instances, and Lambda functions in AWS.

import boto3

# Connect to S3
s3 = boto3.client('s3')

# List all buckets
buckets = s3.list_buckets()
for bucket in buckets['Buckets']:
    print(bucket['Name'])

# Create a new bucket
s3.create_bucket(Bucket='my-new-bucket')

# Upload a file to the bucket
s3.upload_file('file.txt', 'my-new-bucket', 'file.txt')
Enter fullscreen mode Exit fullscreen mode

This script connects to AWS S3, lists all buckets, creates a new bucket, and uploads a file to it.

13. Automating PDF Manipulation

Using the PyPDF2 library, Python can automate tasks like merging, splitting, and extracting text from PDF files.

import PyPDF2

# List of PDF files to merge
pdfs = ['file1.pdf', 'file2.pdf', 'file3.pdf']

# Create a PDF merger object
merger = PyPDF2.PdfMerger()

# Loop through the PDFs and append them to the merger
for pdf in pdfs:
    merger.append(pdf)

# Write the merged PDF to a new file
with open('merged_file.pdf', 'wb') as f:
    merger.write(f)
Enter fullscreen mode Exit fullscreen mode

This script merges multiple PDF files into a single file.

~Trixsec

Top comments (0)