泰国六大闹鬼酒店

【少儿禁】马建《亮出你的舌苔或空空荡荡》

2021年推特网黄粉丝排名Top10 (文末福利)

H游戏只知道《尾行》?弱爆了!丨BB IN

深度解读 | 姜文《让子弹飞》

生成图片,分享到微信朋友圈

自由微信安卓APP发布,立即下载! | 提交文章网址
查看原文

10 个用于日常自动化的 Python 脚本

点击关注👉 Python架构师 2023-02-28

来源:python.plainenglish.io/10-python-scripts-for-everyday-automation-57b75785aaf

翻译 | 杨小爱


在日常生活中,我们会做很多工作,有些是重复的,有些需要手写脚本,如果有一些任务,例如解析 CSV 文件、获取每日头条新闻、编辑照片、发送邮件等等这些简单而重复的任务,如果我们可以使用 Python 自动执行这些任务,是不是会让我们轻松很多?

在今天的文章中,我将向你分享 10 个用于日常任务自动化的 Python 脚本,帮助你提升工作效率,同时,不要忘记收藏好这篇文章,以备留用。

现在,让我们开始吧。

👉点击领取Python面试题手册

Python从入门到进阶知识手册


01、解析 CSV

当你拥有内置的优秀 CSV 解析库时,无需安装像 Pandas 这样的扩展模块。在下面的 python 脚本中,我将向你介绍如何在没有任何外部模块的情况下读取和写入 CSV。

当你需要一个轻量级模块来读取和写入多个 CSV 文件时,此脚本非常方便。

用于 CSV 的轻量级模块;可用于你的 Python 项目。

# Parse CSVimport csvdef Parse_CSV(filename): with open(filename, 'rb') as csvfile: reader = csv.reader(csvfile, delimiter=',', quotechar='|') for row in reader: print(', '.join(row))def Write_CSV(): with open('test.csv', 'wb') as csvfile: w = csv.writer(csvfile, delimiter=',') w.writerow(['Name', 'Age']) w.writerow(['John', '23']) w.writerow(['Mary', '22'])Parse_CSV("test.csv")Write_CSV()

02、压缩大文件

此自动化脚本使用内置的 Zip 文件模块,该模块可帮助你通过压缩大文件的大小来缩小它们的大小,你可以在下面找到可以在单个 zip 文件中压缩多个文件的脚本。

# Compress Large Filesimport zipfile as Zipdef Compressor(files): zip = Zip.ZipFile("output.zip", "w", Zip.ZIP_DEFLATED) for f in files: zip.write(f, compress_type=Zip.ZIP_DEFLATED) zip.close() print("Compressed")Compressor(["video.mkv", "image.jpg"])


03、使用 QR 共享文件


需要以更简单的方式与某人共享文件。然后,此自动化脚本将帮助你创建可以与任何人共享的文件的 QR 码,并且当有人扫描 QR 码时,你共享的文件现在可以下载。


它可以与任何人共享任何文件格式,你可以在你的项目中使用它。

# Share File QrCode# pip install share-file-qr# pip install qrcodeimport subprocess as procimport qrcodedef Share_Files_Qr(file): qr = qrcode.QRCode( version=1, box_size=10, border=4, ) qr.add_data(f"http://192.168.0.105:4000/file/{file}") qr.make(fit=True) qr.make_image().save("qrcode.png") proc.call(f"share-file-qr {file}", stderr=proc.STDOUT)Share_Files_Qr("test.png")


04、Python  Photoshop


使用以下自动化脚本以 Pythonic 方式编辑你的照片,该脚本可让你以编程方式对照片进行 Photoshop 处理。当你处理图像处理项目或需要手动编辑批量图像(如裁剪、翻转、提高质量、压缩大小等)时,此脚本非常方便。


# Python Photoshop# pip install Pillowfrom PIL import Imageimport PIL# loading imageim = Image.open("python.png")# get image infoprint(im.format, im.size, im.mode)# Crop img = im.crop((0, 0, 100, 100))img.save("cropped.png")# Resizeimg = im.resize((100, 100), Image.ANTIALIAS)img.save("resized.png")# Rotateimg = im.rotate(180)img.save("rotated.png")# Flipimg = im.transpose(Image.FLIP_LEFT_RIGHT)img.save("flip.png")# Compress sizeimg.save("python.png", optimize=True, quality=95)# Greyscaleimg = im.convert('L')img.save("grey.png")# Enhance imageenhancer = PIL.ImageEnhance.Contrast(im)enhancer.enhance(1.3)img.save("enhanced_image.png")# Blurimg = im.filter(PIL.ImageFilter.BLUR)img.save("bluring.png")# Drop shadow Effectimg = im.filter(PIL.ImageFilter.GaussianBlur(2))img.save("drop_shadow.png")# Increase brightnessimg = im.point(lambda b: b * 1.2)img.save("bright.png")# merge two imagesimg2 = Image.open("python2.png")img = Image.blend(im, img2, 0.5)img.save("merge.png")

05、获取头条新闻


使用这个 python 脚本获取头条新闻,让自己每天都保持最新状态,该脚本从 NBCnews 网站抓取每日新鲜新闻,并为你提供标题和全文 URL。


它可以用来创建新闻应用,可以在你的新闻项目中使用它。


# Fetch Top Headlines# pip install requests# pip install bs4import requestsfrom bs4 import BeautifulSoupurl = "https://www.nbcnews.com/"response = requests.get(url)html = BeautifulSoup(response.text, "html.parser")for news in html.find_all("h3" ): print("Headline:", news.text) print("Link:", news.find("a")["href"])


06、控制键盘和鼠标


使用这些 Python 脚本以编程方式模拟键盘和鼠标的操作,这个杀手脚本使用鼠标和键盘模块,让你可以通过移动鼠标、单击键、按下和键入等来控制它们。


# Control keyboard and Mouse# pip install mouse# pip install keyboardimport mouseimport keyboard# Move mouse cursormouse.move(100, 100, duration=0.5)# Click mouse left btnmouse.click('left')# Click mouse right btnmouse.click('right')# Click mouse middle btnmouse.click('middle')# Drag mousemouse.drag(100, 100, duration=0.5)# get mouse positionmouse.get_position()# Press keyboard keykeyboard.press('a')# Release keyboard keykeyboard.release('a')# Type on keyboardkeyboard.write('Python Coding')# Press and release keyboard keykeyboard.press_and_release('a')# Combination of keyskeyboard.add_hotkey('ctrl + shift + a')


07、网络状态检查器


通过这个使用 Urllib3 模块的自动化脚本检查任何网站的当前状态,该模块将 HTTP 请求发送到网站,作为响应,我们可以获得当前的 Web 状态。


# Web Status Checker# pip install urllib3import urllib3import timeweb = "https://www.medium.com"http = urllib3.PoolManager()response = http.request('GET', web)if response.status == 200: print("Web is online")else: print("Web is offline")


08、Tkinter 图形用户界面


使用 Tkinter 内置模块创建漂亮而现代的 GUI。这个 Python 原始模块让你可以通过简单的编码创建一个现代的、引人注目的 GUI 应用程序。



# Tkinter GUIfrom tkinter import *pygui = Tk()# Set Screen Titlepygui.title("Python GUI APP")# Set Screen Sizepygui.geometry("1920x1080")# Set Screen Bg Colorpygui.configure(bg="White")# Set Screen Iconpygui.iconbitmap("icon.ico")# Add Label TextText = Label(pygui, text="Medium", font=("Arial", 50))Text.place(x=100, y=100)# Add Buttonsbtn = Button(pygui, text="Hi! Click Me", font=("Arial", 20))btn.place(x=100, y=200)# Add Input Boxvar = StringVar()input = Entry(pygui, textvariable=var, font=("Arial", 20))input.place(x=100, y=300)# Add Text Boxtext = Text(pygui, width=50, height=10)text.place(x=100, y=400)# Add Radio btnsvar = IntVar()radio1 = Radiobutton(pygui, text="Option 1", variable=var, value=1)radio1.place(x=100, y=500)# Add Checkboxesvar = IntVar()check = Checkbutton(pygui, text="Check Me", variable=var)check.place(x=100, y=600)# Add Imageimg = PhotoImage(file="image.png")image = Label(pygui, image=img)image.place(x=100, y=600)# looppygui.mainloop()


09、抖音下载器


现在,你可以通过编程方式下载你喜爱的 Tiktok 视频。下面的自动化脚本将使你更容易用几行代码下载一堆 TikTok 视频。


# Tiktok Video Downloader# pip install selenium # pip install webdriver-manager# pip install beautifulsoup4from selenium import webdriver as webfrom webdriver_manager.chrome import *import timefrom bs4 import BeautifulSoup as bsimport urllib.requestdef tiktok_downloader(url): op = web.ChromeOptions() op.add_argument('--headless') driver = web.Chrome(ChromeDriverManager().install(), options=op) driver.get(url) time.sleep(5) html = driver.page_source soup = bs(html, 'html.parser') video = soup.find('video') urllib.request.urlretrieve(video['src'], 'video.mp4')tiktok_downloader("https://www.tiktok.com/video/xxxx")


10、请求 HTML


使用 requests_html 模块获取静态和动态网页,该脚本是请求模块的修改版本,用于获取 JS 加载网页。


# Request HTML# pip install requests_htmlfrom requests_html import HTMLSessionurl = 'https://www.google.com/search?q=python'session = HTMLSession()req = session.get(url, timeout=20)req.html.render(sleep=1)print(req.status_code)print(req.html.html)


写在最后的想法


关于这个Python自动化的脚本,我在前面也分享了一些,如果你是python的爱好者,一定要好好利用python做它能够为你做的事情,提升效率,Python真的是个好语言,值得大家学习与拥有。



程序员技术交流群


扫码进群记得备注:城市、昵称和技术方向


 阅读更多


  1. YYDS!轻松用Python控制你的手机
  2. 【Pycharm教程】详解 PyCharm 断点
  3. 20个非常有用的Python单行代码

文章有问题?点此查看未经处理的缓存