欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > ​十个常见的 Python 脚本 (详细介绍 + 代码举例)

​十个常见的 Python 脚本 (详细介绍 + 代码举例)

2024/10/25 4:19:57 来源:https://blog.csdn.net/qq_36807888/article/details/140862595  浏览:    关键词:​十个常见的 Python 脚本 (详细介绍 + 代码举例)

1. 批量重命名文件

介绍:  该脚本用于批量重命名指定目录下的文件,例如将所有 ".txt" 文件重命名为 ".md" 文件。

import osdef batch_rename(directory, old_ext, new_ext):"""批量重命名文件扩展名。Args:directory: 要处理的目录路径。old_ext: 要替换的旧扩展名。new_ext: 要替换的新扩展名。"""for filename in os.listdir(directory):if filename.endswith(old_ext):base_name = os.path.splitext(filename)[0]new_filename = base_name + new_extold_path = os.path.join(directory, filename)new_path = os.path.join(directory, new_filename)os.rename(old_path, new_path)# 示例用法:将当前目录下所有 ".txt" 文件重命名为 ".md" 文件
batch_rename(".", ".txt", ".md")

2. 下载网页图片

介绍:  该脚本用于下载指定网页上的所有图片,并保存到本地目录。

import requests
from bs4 import BeautifulSoup
import osdef download_images(url, save_dir):"""下载网页上的所有图片。Args:url: 要下载图片的网页地址。save_dir: 保存图片的目录路径。"""response = requests.get(url)soup = BeautifulSoup(response.text, 'html.parser')# 创建保存目录if not os.path.exists(save_dir):os.makedirs(save_dir)# 找到所有图片标签img_tags = soup.find_all('img')# 下载每张图片for i, img_tag in enumerate(img_tags):img_url = img_tag.get('src')if img_url:img_data = requests.get(img_url).contentimg_name = f"image_{i+1}.jpg"img_path = os.path.join(save_dir, img_name)with open(img_path, 'wb') as f:f.write(img_data)print(f"Downloaded: {img_name}")# 示例用法:下载百度首页的图片
download_images("https://www.baidu.com", "baidu_images")

3. 发送邮件通知

介绍: 该脚本用于发送邮件通知,例如在脚本执行完毕后发送邮件通知管理员。

import smtplib
from email.mime.text import MIMETextdef send_email(sender_email, sender_password, receiver_email, subject, message):"""发送邮件通知。Args:sender_email: 发送方邮箱地址。sender_password: 发送方邮箱密码。receiver_email: 接收方邮箱地址。subject: 邮件主题。message: 邮件内容。"""msg = MIMEText(message, 'plain', 'utf-8')msg['Subject'] = subjectmsg['From'] = sender_emailmsg['To'] = receiver_emailtry:with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:smtp.login(sender_email, sender_password)smtp.send_message(msg)print("邮件发送成功!")except Exception as e:print(f"邮件发送失败:{e}")# 示例用法:发送邮件通知
send_email("your_email@gmail.com", "your_password", "receiver@example.com", "脚本执行完毕", "脚本已成功执行!")

4. 读取 CSV 文件

介绍: 该脚本用于读取 CSV 文件,并可以根据需要对数据进行处理和分析。

import csvdef read_csv(file_path):"""读取 CSV 文件。Args:file_path: CSV 文件路径。"""with open(file_path, 'r', encoding='utf-8') as f:reader = csv.reader(f)# 跳过标题行next(reader)for row in reader:print(row)# 示例用法:读取名为 "data.csv" 的 CSV 文件
read_csv("data.csv")

5. 写入 CSV 文件

介绍:  该脚本用于将数据写入 CSV 文件,可以用于数据存储和导出。

import csvdef write_csv(file_path, data):"""将数据写入 CSV 文件。Args:file_path: CSV 文件路径。data: 要写入的数据,格式为列表的列表。"""with open(file_path, 'w', encoding='utf-8', newline='') as f:writer = csv.writer(f)writer.writerows(data)# 示例用法:将数据写入名为 "data.csv" 的 CSV 文件
data = [["Name", "Age", "City"],["Alice", 25, "New York"],["Bob", 30, "London"],
]
write_csv("data.csv", data)

6. 爬取网页数据

介绍:  该脚本用于爬取网页数据,例如新闻标题、商品价格等,并可以将数据保存到本地或数据库。

import requests
from bs4 import BeautifulSoupdef scrape_website(url):"""爬取网页数据。Args:url: 要爬取数据的网页地址。"""response = requests.get(url)soup = BeautifulSoup(response.text, 'html.parser')# 提取数据,例如新闻标题titles = [title.text.strip() for title in soup.find_all('h2', class_='news-title')]# 打印提取的数据for title in titles:print(title)# 示例用法:爬取新浪新闻首页的新闻标题
scrape_website("https://news.sina.com.cn/")

7. 自动化测试

介绍:  该脚本用于自动化测试软件或网站的功能,例如登录测试、表单提交测试等。

from selenium import webdriverdef test_login(url, username, password):"""测试网站登录功能。Args:url: 要测试的网站地址。username: 登录用户名。password: 登录密码。"""driver = webdriver.Chrome()driver.get(url)# 找到用户名和密码输入框,并输入用户名和密码username_input = driver.find_element_by_id("username")password_input = driver.find_element_by_id("password")username_input.send_keys(username)password_input.send_keys(password)# 找到登录按钮,并点击login_button = driver.find_element_by_id("login-button")login_button.click()# 检查是否登录成功if driver.current_url == "https://www.example.com/dashboard":print("登录成功!")else:print("登录失败!")driver.quit()# 示例用法:测试 example.com 网站的登录功能
test_login("https://www.example.com/login", "testuser", "testpassword")

8. 图像处理

介绍:  该脚本用于图像处理,例如裁剪、缩放、添加水印等。

from PIL import Imagedef resize_image(image_path, width, height):"""缩放图片大小。Args:image_path: 图片路径。width: 新的宽度。height: 新的高度。"""img = Image.open(image_path)img = img.resize((width, height))img.save("resized_" + image_path)# 示例用法:将图片 "image.jpg" 缩放为 200x200 像素
resize_image("image.jpg", 200, 200)

9. 数据可视化

介绍:  该脚本用于数据可视化,例如绘制图表、生成报表等,可以更直观地展示数据。

import matplotlib.pyplot as pltdef plot_chart(x, y):"""绘制折线图。Args:x: x 轴数据。y: y 轴数据。"""plt.plot(x, y)plt.xlabel("X 轴")plt.ylabel("Y 轴")plt.title("折线图")plt.show()# 示例用法:绘制 x=[1,2,3], y=[4,5,6] 的折线图
plot_chart([1, 2, 3], [4, 5, 6])

10. 创建简单的 Web 应用

介绍:  该脚本使用 Flask 框架创建一个简单的 Web 应用,例如显示 "Hello, world!" 的页面。

from flask import Flaskapp = Flask(__name__)@app.route("/")
def hello():return "Hello, world!"if __name__ == "__main__":app.run(debug=True)

注意:  以上代码示例仅供参考,实际应用中需要根据具体需求进行修改和完善。部署爬虫相关代码需要遵守 robots 协议, 并注意数据安全。

如果对你有帮助,记得点赞分享支持一下~

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com