
作者:天津九安特機電工程有限公司 來(lái)源: 天津九安特機電工程有限公司 日期:2026-05-05 08:41:44
1、壓縮安裝Python??和相關(guān)庫
確保你的圖片計算機上已經(jīng)安裝了Python,使用pip安裝以下庫:
Pillow:用于處理圖像的輸入庫
Beauti(◎_◎;)fulSoup:用于解析HTML的庫
pip install Pillowpip install beautiful??sou┐(′д`)┌p4
2、編寫(xiě)Python腳本
創(chuàng )建一個(gè)名為compress_images.py的批量文件,并在其中編寫(xiě)以下代碼:
impヽ(′?`)ノort osfrom PIL import Imagefrom bs??4 import Beaヽ(′?`)ノutifulSoupdef compress_image(input_file,壓(ya)縮 output_fi( ???)le, quality=85): image = Image.open=""(input_file) image.save(output_file, optimize=True, quality=quality)def compress_images_in_html(input_html, output_html): with open=""(input_html, 'r', encoding='utf8') as file: so(′?`)up = Beau??tifulSoup(file, 'html.parser') for img in soup.find_all('img'): img_src = img['src'] img_name, img_ext = os.path.splitext(img_src) compressed_img_src = f"{ img_name}_compressed{ im(?⊿?)g_ext}" compress_image(img_src, compressed_img_src) img['sr??c'] = compressed_img_src with open(output_html, 'w', encoding='utf8') as file: file.(′?`)write(ヽ(′?`)ノstr(soup))if __name__ == "__main__": input_htm??l = &quo??t;input.html" output_html = &q??uot;output.(//ω//)html" compress_images_in_html(input_html, output_html)3、運行腳本
將你要壓縮的圖片圖片放入與co??mpress_images.py相同的文件夾中,在命令行中運行以下命令:
py(╬?益?)thon compress_images.py這將生成一個(gè)名為output.html的??輸入新文件,其中包含壓縮后的批量圖片。