0

0

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

DDD

DDD

发布时间:2024-10-19 08:09:14

|

802人浏览过

|

来源于dev.to

转载

如何使用 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 获取指定城市的当前天气数据并显示它。

立即学习Python免费学习笔记(深入)”;

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 文件管理

Pascal基础教程 Pascal入门必备基础教程 CHM版
Pascal基础教程 Pascal入门必备基础教程 CHM版

无论做任何事情,都要有一定的方式方法与处理步骤。计算机程序设计比日常生活中的事务处理更具有严谨性、规范性、可行性。为了使计算机有效地解决某些问题,须将处理步骤编排好,用计算机语言组成“序列”,让计算机自动识别并执行这个用计算机语言组成的“序列”,完成预定的任务。将处理问题的步骤编排好,用计算机语言组成序列,也就是常说的编写程序。在Pascal语言中,执行每条语句都是由计算机完成相应的操作。编写Pascal程序,是利用Pasca

下载

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开发工具
python开发工具

php中文网为大家提供各种python开发工具,好的开发工具,可帮助开发者攻克编程学习中的基础障碍,理解每一行源代码在程序执行时在计算机中的过程。php中文网还为大家带来python相关课程以及相关文章等内容,供大家免费下载使用。

759

2023.06.15

python打包成可执行文件
python打包成可执行文件

本专题为大家带来python打包成可执行文件相关的文章,大家可以免费的下载体验。

639

2023.07.20

python能做什么
python能做什么

python能做的有:可用于开发基于控制台的应用程序、多媒体部分开发、用于开发基于Web的应用程序、使用python处理数据、系统编程等等。本专题为大家提供python相关的各种文章、以及下载和课程。

762

2023.07.25

format在python中的用法
format在python中的用法

Python中的format是一种字符串格式化方法,用于将变量或值插入到字符串中的占位符位置。通过format方法,我们可以动态地构建字符串,使其包含不同值。php中文网给大家带来了相关的教程以及文章,欢迎大家前来阅读学习。

618

2023.07.31

python教程
python教程

Python已成为一门网红语言,即使是在非编程开发者当中,也掀起了一股学习的热潮。本专题为大家带来python教程的相关文章,大家可以免费体验学习。

1265

2023.08.03

python环境变量的配置
python环境变量的配置

Python是一种流行的编程语言,被广泛用于软件开发、数据分析和科学计算等领域。在安装Python之后,我们需要配置环境变量,以便在任何位置都能够访问Python的可执行文件。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

549

2023.08.04

python eval
python eval

eval函数是Python中一个非常强大的函数,它可以将字符串作为Python代码进行执行,实现动态编程的效果。然而,由于其潜在的安全风险和性能问题,需要谨慎使用。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

579

2023.08.04

scratch和python区别
scratch和python区别

scratch和python的区别:1、scratch是一种专为初学者设计的图形化编程语言,python是一种文本编程语言;2、scratch使用的是基于积木的编程语法,python采用更加传统的文本编程语法等等。本专题为大家提供scratch和python相关的文章、下载、课程内容,供大家免费下载体验。

709

2023.08.11

高德地图升级方法汇总
高德地图升级方法汇总

本专题整合了高德地图升级相关教程,阅读专题下面的文章了解更多详细内容。

71

2026.01.16

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
MySQL 教程
MySQL 教程

共48课时 | 1.8万人学习

MySQL 初学入门(mosh老师)
MySQL 初学入门(mosh老师)

共3课时 | 0.3万人学习

简单聊聊mysql8与网络通信
简单聊聊mysql8与网络通信

共1课时 | 801人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号