我的知识记录

Python 批量下载图片:从网页抓取所有图片

import os
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
 
def download_images(url, folder='images'):
    os.makedirs(folder, exist_ok=True)
    html = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'}).text
    soup = BeautifulSoup(html, 'html.parser')
    count = 0
    for img in soup.find_all('img'):
        src = img.get('src')
        if not src:
            continue
        src = urljoin(url, src)
        try:
            data = requests.get(src, timeout=10).content
            ext = os.path.splitext(src)[1].split('?')[0] or '.jpg'
            with open(os.path.join(folder, f'{count:03d}{ext}'), 'wb') as f:
                f.write(data)
            count += 1
        except Exception:
            pass
    print(f"共下载 {count} 张图片")
 
download_images('https://www.example.com')

Python 批量下载图片:从网页抓取所有图片

标签:

更新时间:2026-09-14 13:41:39

上一篇:Python 视频压缩:一键减小视频体积

下一篇:Python 定时关机:到点自动关机 / 重启