天天看點

【源碼】10個Python腳本來自動化你的日常任務!

那麼在本文中,将向您介紹 10 個 Python 自動化腳本,以使你的工作更加自動化,生活更加輕松。是以,沒有更多的重複任務将這篇文章放在您的清單中,讓我們開始吧。

【源碼】10個Python腳本來自動化你的日常任務!

01、解析和提取 HTML

此自動化腳本将幫助你從網頁 URL 中提取 HTML,然後還為你提供可用于解析 HTML 以擷取資料的功能。這個很棒的腳本對于網絡爬蟲和那些想要解析 HTML 以擷取重要資料的人來說是一種很好的享受。

# Parse and Extract HTML
# pip install gazpacho
import gazpacho
# Extract HTML from URL
url = 'https://www.example.com/'
html = gazpacho.get(url)
print(html)
# Extract HTML with Headers
headers = {'User-Agent': 'Mozilla/5.0'}
html = gazpacho.get(url, headers=headers)
print(html)
# Parse HTML
parse = gazpacho.Soup(html)
# Find single tags
tag1 = parse.find('h1')
tag2 = parse.find('span')
# Find multiple tags
tags1 = parse.find_all('p')
tags2 = parse.find_all('a')
# Find tags by class
tag = parse.find('.class')
# Find tags by Attribute
tag = parse.find("div", attrs={"class": "test"})
# Extract text from tags
text = parse.find('h1').text
text = parse.find_all('p')[0].text
           

02、二維碼掃描器

擁有大量二維碼圖像或隻想掃描二維碼圖像,那麼此自動化腳本将幫助你。該腳本使用 Qrtools 子產品,使你能夠以程式設計方式掃描 QR 圖像。

# Qrcode Scanner
# pip install qrtools
from qrtools import Qr
def Scan_Qr(qr_img):
    qr = Qr()
    qr.decode(qr_img)
    print(qr.data)
    return qr.data
print("Your Qr Code is: ", Scan_Qr("qr.png"))
           

03、截圖

現在,你可以使用下面這個很棒的腳本以程式設計方式截取螢幕截圖。使用此腳本,你可以直接截屏或截取特定區域的螢幕截圖。

# Grab Screenshot
# pip install pyautogui
# pip install Pillow
from pyautogui import screenshot
import time
from PIL import ImageGrab
# Grab Screenshot of Screen
def grab_screenshot():
    shot = screenshot()
    shot.save('my_screenshot.png')
# Grab Screenshot of Specific Area
def grab_screenshot_area():
    area = (0, 0, 500, 500)
    shot = ImageGrab.grab(area)
    shot.save('my_screenshot_area.png')
# Grab Screenshot with Delay
def grab_screenshot_delay():
    time.sleep(5)
    shot = screenshot()
    shot.save('my_screenshot_delay.png')
           

04、建立有聲讀物

厭倦了手動将您的 PDF 書籍轉換為有聲讀物,那麼這是你的自動化腳本,它使用 GTTS 子產品将你的 PDF 文本轉換為音頻。

# Create Audiobooks
# pip install gTTS
# pip install PyPDF2
from PyPDF2 import PdfFileReader as reader
from gtts import gTTS
def create_audio(pdf_file):
    read_Pdf = reader(open(pdf_file, 'rb'))
    for page in range(read_Pdf.numPages):
        text = read_Pdf.getPage(page).extractText()
        tts = gTTS(text, )
        tts.save('page' + str(page) + '.mp3')
create_audio('book.pdf')
           

05、PDF 編輯器

使用以下自動化腳本使用 Python 編輯 PDF 檔案。該腳本使用 PyPDF4 子產品,它是 PyPDF2 的更新版本,下面我編寫了 Parse Text、Remove pages 等常用功能。

當你有大量 PDF 檔案要編輯或需要以程式設計方式在 Python 項目中使用腳本時,這是一個友善的腳本。

# PDF Editor
# pip install PyPDf4
import PyPDF4
# Parse the Text from PDF
def parse_text(pdf_file):
    reader = PyPDF4.PdfFileReader(pdf_file)
    for page in reader.pages:
        print(page.extractText())
# Remove Page from PDF
def remove_page(pdf_file, page_numbers):
    filer = PyPDF4.PdfReader('source.pdf', 'rb')
    out = PyPDF4.PdfWriter()
    for index in page_numbers:
        page = filer.pages[index] 
        out.add_page(page)
with open('rm.pdf', 'wb') as f:
        out.write(f)
# Add Blank Page to PDF
def add_page(pdf_file, page_number):
    reader = PyPDF4.PdfFileReader(pdf_file)
    writer = PyPDF4.PdfWriter()
    writer.addPage()
    with open('add.pdf', 'wb') as f:
        writer.write(f)
# Rotate Pages
def rotate_page(pdf_file):
    reader = PyPDF4.PdfFileReader(pdf_file)
    writer = PyPDF4.PdfWriter()
    for page in reader.pages:
        page.rotateClockwise(90)
        writer.addPage(page)
    with open('rotate.pdf', 'wb') as f:
        writer.write(f)
# Merge PDFs
def merge_pdfs(pdf_file1, pdf_file2):
    pdf1 = PyPDF4.PdfFileReader(pdf_file1)
    pdf2 = PyPDF4.PdfFileReader(pdf_file2)
    writer = PyPDF4.PdfWriter()
    for page in pdf1.pages:
        writer.addPage(page)
    for page in pdf2.pages:
        writer.addPage(page)
    with open('merge.pdf', 'wb') as f:
        writer.write(f)
           

06、迷你 Stackoverflow

作為一名程式員,我知道我們每天都需要 StackOverflow,但你不再需要在 Google 上搜尋它。現在,在您繼續處理項目的同時,在你的 CMD 中獲得直接解決方案。通過使用 Howdoi 子產品,你可以在指令提示符或終端中獲得 StackOverflow 解決方案。你可以在下面找到一些可以嘗試的示例。

# Automate Stackoverflow
# pip install howdoi
# Get Answers in CMD
#example 1
> howdoi how do i install python3
# example 2
> howdoi selenium Enter keys
# example 3
> howdoi how to install modules
# example 4
> howdoi Parse html with python
# example 5
> howdoi int not iterable error
# example 6
> howdoi how to parse pdf with python
# example 7
> howdoi Sort list in python
# example 8
> howdoi merge two lists in python
# example 9
>howdoi get last element in list python
# example 10
> howdoi fast way to sort list
           

07、自動化手機

此自動化腳本将幫助你使用 Python 中的 Android 調試橋 (ADB) 自動化你的智能手機。下面我将展示如何自動執行常見任務,例如滑動手勢、呼叫、發送短信等等。

您可以了解有關 ADB 的更多資訊,并探索更多令人興奮的方法來實作手機自動化,讓您的生活更輕松。

# Automate Mobile Phones
# pip install opencv-python
import subprocess
def main_adb(cm):
    p = subprocess.Popen(cm.split(' '), stdout=subprocess.PIPE, shell=True)
    (output, _) = p.communicate()
    return output.decode('utf-8')
# Swipe 
def swipe(x1, y1, x2, y2, duration):
    cmd = 'adb shell input swipe {} {} {} {} {}'.format(x1, y1, x2, y2, duration)
    return main_adb(cmd)
# Tap or Clicking
def tap(x, y):
    cmd = 'adb shell input tap {} {}'.format(x, y)
    return main_adb(cmd)
# Make a Call
def make_call(number):
    cmd = f"adb shell am start -a android.intent.action.CALL -d tel:{number}"
    return main_adb(cmd)
# Send SMS
def send_sms(number, message):
    cmd = 'adb shell am start -a android.intent.action.SENDTO -d  sms:{} --es sms_body "{}"'.format(number, message)
    return main_adb(cmd)
# Download File From Mobile to PC
def download_file(file_name):
    cmd = 'adb pull /sdcard/{}'.format(file_name)
    return main_adb(cmd)
# Take a screenshot
def screenshot():
    cmd = 'adb shell screencap -p'
    return main_adb(cmd)
# Power On and Off
def power_off():
    cmd = '"adb shell input keyevent 26"'
    return main_adb(cmd)
           

08、監控 CPU/GPU 溫度

你可能使用 CPU-Z 或任何規格監控軟體來捕獲你的 Cpu 和 Gpu 溫度,但你也可以通過程式設計方式進行。好吧,這個腳本使用 Pythonnet 和 OpenhardwareMonitor 來幫助你監控目前的 Cpu 和 Gpu 溫度。

你可以使用它在達到一定溫度時通知自己,也可以在 Python 項目中使用它來簡化日常生活。

# Get CPU/GPU Temperature
# pip install pythonnet
import clr
clr.AddReference("OpenHardwareMonitorLib")
from OpenHardwareMonitorLib import *
spec = Computer()
spec.GPUEnabled = True
spec.CPUEnabled = True
spec.Open()
# Get CPU Temp
def Cpu_Temp():
    while True:
        for cpu in range(0, len(spec.Hardware[0].Sensors)):
            if "/temperature" in str(spec.Hardware[0].Sensors[cpu].Identifier):
                print(str(spec.Hardware[0].Sensors[cpu].Value))
# Get GPU Temp
def Gpu_Temp()
    while True:
        for gpu in range(0, len(spec.Hardware[0].Sensors)):
            if "/temperature" in str(spec.Hardware[0].Sensors[gpu].Identifier):
                print(str(spec.Hardware[0].Sensors[gpu].Value))
           

09、Instagram 上傳機器人

Instagram 是一個著名的社交媒體平台,你現在不需要通過智能手機上傳照片或視訊。你可以使用以下腳本以程式設計方式執行此操作。

# Upload Photos and Video on Insta
# pip install instabot
from instabot import Bot
def Upload_Photo(img):
    robot = Bot()
    robot.login(username="user", password="pass")
    robot.upload_photo(img, caption="Medium Article")
    print("Photo Uploaded")
def Upload_Video(video):
    robot = Bot()
    robot.login(username="user", password="pass")
    robot.upload_video(video, caption="Medium Article")
    print("Video Uploaded")
def Upload_Story(img):
    robot = Bot()
    robot.login(username="user", password="pass")
    robot.upload_story(img, caption="Medium Article")
    print("Story Photos Uploaded")
Upload_Photo("img.jpg")
Upload_Video("video.mp4")
           

10、視訊水印

使用此自動化腳本為你的視訊添加水印,該腳本使用 Moviepy,這是一個友善的視訊編輯子產品。在下面的腳本中,你可以看到如何添加水印并且可以自由使用它。

# Video Watermark with Python
# pip install moviepy
from moviepy.editor import *
clip = VideoFileClip("myvideo.mp4", audio=True) 
width,height = clip.size  
text = TextClip("WaterMark", font='Arial', color='white', fontsize=28)
set_color = text.on_color(size=(clip.w + text.w, text.h-10), color=(0,0,0), pos=(6,'center'), col_opacity=0.6)
set_textPos = set_color.set_pos( lambda pos: (max(width/30,int(width-0.5* width* pos)),max(5*height/6,int(100* pos))) )
Output = CompositeVideoClip([clip, set_textPos])
Output.duration = clip.duration
Output.write_videofile("output.mp4", fps=30, codec='libx264')
           

關于Python技術儲備

學好 Python 不論是就業還是做副業賺錢都不錯,但要學會 Python 還是要有一個學習規劃。最後大家分享一份全套的 Python 學習資料,給那些想學習 Python 的小夥伴們一點幫助!

一、Python所有方向的學習路線

Python所有方向的技術點做的整理,形成各個領域的知識點彙總,它的用處就在于,你可以按照上面的知識點去找對應的學習資源,保證自己學得較為全面。

【源碼】10個Python腳本來自動化你的日常任務!

二、Python必備開發工具

【源碼】10個Python腳本來自動化你的日常任務!

四、Python視訊合集

觀看零基礎學習視訊,看視訊學習是最快捷也是最有效果的方式,跟着視訊中老師的思路,從基礎到深入,還是很容易入門的。

【源碼】10個Python腳本來自動化你的日常任務!

五、實戰案例

光學理論是沒用的,要學會跟着一起敲,要動手實操,才能将自己的所學運用到實際當中去,這時候可以搞點實戰案例來學習。

【源碼】10個Python腳本來自動化你的日常任務!

六、Python練習題

檢查學習結果。

【源碼】10個Python腳本來自動化你的日常任務!

七、面試資料

我們學習Python必然是為了找到高薪的工作,下面這些面試題是來自阿裡、騰訊、位元組等一線網際網路大廠最新的面試資料,并且有阿裡大佬給出了權威的解答,刷完這一套面試資料相信大家都能找到滿意的工作。

【源碼】10個Python腳本來自動化你的日常任務!
【源碼】10個Python腳本來自動化你的日常任務!

這份完整版的Python全套學習資料已經上傳CSDN,朋友們如果需要可以微信掃描下方CSDN官方認證二維碼免費領取【保證100%免費】

【源碼】10個Python腳本來自動化你的日常任務!