如何使用 Python 自动执行日常任务(第 2 部分)

如何使用 python 自动执行日常任务(第 2 部分)

作者:特里克斯·赛勒斯

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 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')

此脚本连接到 aws s3,列出所有存储桶,创建一个新存储桶,并向其中上传文件。

13。自动化 pdf 操作

使用 pypdf2 库,python 可以自动执行合并、拆分和从 pdf 文件中提取文本等任务。

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)

此脚本将多个 pdf 文件合并为一个文件。

~trixsec

以上就是如何使用 Python 自动执行日常任务(第 2 部分)的详细内容,更多请关注www.sxiaw.com其它相关文章!