如何使用 Python 自動執行日常任務(第 2 部分)

DDD
發布: 2024-10-19 06:15:01
原創
762 人瀏覽過

How to Automate Everyday Tasks with Python (Part 2)

作者:Trix Cyrus

Waymap滲透測試工具:點這裡
TrixSec Github:點這裡

在第 1 部分中,我們探索如何使用 Python 來自動化文件管理、網頁抓取、發送電子郵件、Google 表格和系統監控。在第 2 部分中,我們將繼續介紹更高級的任務,例如自動化 API、調度腳本以及將自動化與第三方服務整合。

7。自動化 API 請求

許多 Web 服務提供 API 來以程式設計方式與其平台進行互動。使用請求庫,您可以輕鬆地自動執行任務,例如從 API 取得資料、發布更新或在雲端服務上執行 CRUD 操作。

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}")
登入後複製
登入後複製

此腳本從 OpenWeatherMap API 取得指定城市的當前天氣資料並顯示它。

8。使用 Python 排程任務

有時您需要自動執行任務以在特定時間或間隔運行。 Python 的計劃庫可以輕鬆設定在特定時間自動執行的作​​業。

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)
登入後複製
登入後複製

此腳本安排任務在每天上午 9 點運行,使用簡單的調度循環來保持任務運行。

9。自動化資料庫操作

Python 可用於與資料庫互動、自動輸入資料以及執行讀取、更新和刪除記錄等操作。 sqlite3 模組可讓您管理 SQLite 資料庫,而其他程式庫(如 psycopg2 或 MySQLdb)可與 PostgreSQL 和 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()
登入後複製

此腳本建立一個 SQLite 資料庫,新增一個「任務」表,並在資料庫中插入一個新任務。

10。自動化 Excel 檔案管理

Python 與 openpyxl 或 pandas 函式庫一起可用於自動讀取、寫入和修改 Excel 檔案。這對於自動化數據分析和報告任務特別有用。

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)
登入後複製

此腳本讀取 Excel 文件,對資料執行計算,並將更新的資料寫入新文件。

11。使用 Selenium 實現瀏覽器互動自動化

使用 Selenium,Python 可以自動執行與 Web 瀏覽器的交互,例如登入帳戶、填寫表單和執行重複的 Web 任務。

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()
登入後複製

此腳本開啟 Web 瀏覽器,導覽至登入頁面,填寫憑證,然後自動登入。

12。自動化雲端服務

Python 與 AWS、Google Cloud 和 Azure 等雲端服務整合良好。使用 boto3 函式庫,您可以自動執行管理 AWS 中的 S3 儲存桶、EC2 執行個體和 Lambda 函數等任務。

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}")
登入後複製
登入後複製

此腳本連接到 AWS S3,列出所有儲存桶,建立一個新儲存桶,並向其中上傳檔案。

13。自動化 PDF 操作

使用 PyPDF2 函式庫,Python 可以自動執行合併、分割和從 PDF 檔案中提取文字等任務。

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)
登入後複製
登入後複製

此腳本將多個 PDF 檔案合併為一個檔案。

~Trixsec

以上是如何使用 Python 自動執行日常任務(第 2 部分)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!