八个拿来即用的Python自动化脚本!("实用Python自动化脚本大集合:八个可直接上手的项目!")
原创
一、自动下载网页图片
在互联网上,我们频繁需要下载一些图片,但是手动下载非常耗时。以下是一个使用Python的自动化脚本,可以帮助你敏捷下载网页中的所有图片。
import os
import requests
from bs4 import BeautifulSoup
def download_images(url, download_path):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
images = soup.find_all('img')
if not os.path.exists(download_path):
os.makedirs(download_path)
for img in images:
img_url = img.get('src')
img_name = img_url.split('/')[-1]
img_response = requests.get(img_url)
with open(f"{download_path}/{img_name}", 'wb') as f:
f.write(img_response.content)
if __name__ == '__main__':
url = 'https://example.com'
download_path = 'downloaded_images'
download_images(url, download_path)
print("图片下载完成!")
二、自动发送邮件
有时候我们需要定时发送邮件,以下是一个Python脚本,可以帮助你自动化发送邮件。
import smtplib
from email.mime.text import MIMEText
from email.header import Header
def send_email(smtp_host, smtp_port, username, password, recipient, subject, body):
msg = MIMEText(body, 'plain', 'utf-8')
msg['From'] = username
msg['To'] = recipient
msg['Subject'] = Header(subject, 'utf-8')
server = smtplib.SMTP(smtp_host, smtp_port)
server.starttls()
server.login(username, password)
server.sendmail(username, [recipient], msg.as_string())
server.quit()
if __name__ == '__main__':
smtp_host = 'smtp.example.com'
smtp_port = 465
username = 'your_email@example.com'
password = 'your_password'
recipient = 'recipient@example.com'
subject = '测试邮件'
body = '这是一封测试邮件。'
send_email(smtp_host, smtp_port, username, password, recipient, subject, body)
print("邮件发送成就!")
三、自动备份文件到云盘
为了防止数据丢失,我们可以定期将文件备份到云盘。以下是一个使用Python的脚本,可以自动将文件上传到云盘。
import os
import requests
def backup_to_cloud(file_path, cloud_url, access_token):
files = {'file': open(file_path, 'rb')}
headers = {'Authorization': f'Bearer {access_token}'}
response = requests.post(cloud_url, files=files, headers=headers)
return response.status_code
if __name__ == '__main__':
file_path = 'path/to/your/file'
cloud_url = 'https://cloud.example.com/upload'
access_token = 'your_access_token'
status_code = backup_to_cloud(file_path, cloud_url, access_token)
if status_code == 200:
print("文件备份成就!")
else:
print("文件备份未果!")
四、自动处理Excel文件
在数据处理过程中,我们频繁需要处理Excel文件。以下是一个Python脚本,可以自动读取、修改和保存Excel文件。
import pandas as pd
def process_excel(file_path, new_file_path):
df = pd.read_excel(file_path)
df['新列'] = '新值'
df.to_excel(new_file_path, index=False)
if __name__ == '__main__':
file_path = 'path/to/your/excel_file.xlsx'
new_file_path = 'path/to/your/new_excel_file.xlsx'
process_excel(file_path, new_file_path)
print("Excel文件处理完成!")
五、自动抓取网站数据
在互联网上,有很多有用的数据。以下是一个Python脚本,可以帮助你自动抓取网站数据。
import requests
from bs4 import BeautifulSoup
def crawl_data(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
data = []
for item in soup.find_all('div', class_='item'):
title = item.find('h2').text
description = item.find('p').text
data.append({'title': title, 'description': description})
return data
if __name__ == '__main__':
url = 'https://example.com'
data = crawl_data(url)
print(data)
六、自动分析股票数据
股票投资是很多人关心的话题。以下是一个Python脚本,可以帮助你分析股票数据。
import pandas as pd
import matplotlib.pyplot as plt
def analyze_stock_data(file_path):
df = pd.read_csv(file_path)
df['日期'] = pd.to_datetime(df['日期'])
df.set_index('日期', inplace=True)
plt.figure(figsize=(10, 6))
plt.plot(df.index, df['收盘价'], label='收盘价')
plt.plot(df.index, df['开盘价'], label='开盘价')
plt.title('股票价格走势图')
plt.xlabel('日期')
plt.ylabel('价格')
plt.legend()
plt.show()
if __name__ == '__main__':
file_path = 'path/to/your/stock_data.csv'
analyze_stock_data(file_path)
七、自动监控文件夹变化
在某些场景下,我们需要监控文件夹中的文件变化。以下是一个Python脚本,可以自动监控文件夹变化。
import os
import time
def monitor_directory(directory):
last_files = set(os.listdir(directory))
while True:
current_files = set(os.listdir(directory))
new_files = current_files - last_files
if new_files:
print("发现新文件:", new_files)
last_files = current_files
time.sleep(10)
if __name__ == '__main__':
directory = 'path/to/your/directory'
monitor_directory(directory)
八、自动生成网站地图
网站地图对于搜索引擎优化非常重要。以下是一个Python脚本,可以帮助你自动生成网站地图。
import os
import xml.etree.ElementTree as ET
def generate_sitemap(url, output_path):
root = ET.Element('urlset', xmlns='http://www.sitemaps.org/schemas/sitemap/0.9')
for page in ['index', 'about', 'contact']:
url_element = ET.SubElement(root, 'url')
loc_element = ET.SubElement(url_element, 'loc')
loc_element.text = f"{url}/{page}"
tree = ET.ElementTree(root)
tree.write(output_path)
if __name__ == '__main__':
url = 'https://example.com'
output_path = 'path/to/your/sitemap.xml'
generate_sitemap(url, output_path)
print("网站地图生成完成!")
以上就是八个实用的Python自动化脚本,可以帮助你减成本时间工作效能。愿望对你有所帮助!