Python批量下载网页图片

代码脚本 · 其他

Python编写的图片批量下载工具,输入网页URL自动提取所有图片链接,批量下载到本地,自动去重,支持自定义保存路径,跳过已下载的图片,支持设置请求头避免被封。

详细内容

import requests, os, hashlib from bs4 import BeautifulSoup url = 'https://example.com' save_dir = 'images' os.makedirs(save_dir, exist_ok=True) headers = {'User-Agent': 'Mozilla/5.0'} resp = requests.get(url, headers=headers) soup = BeautifulSoup(resp.text, 'html.parser') for img in soup.find_all('img'): src = img.get('src') or img.get('data-src') if not src or not src.startswith('http'): continue try: r = requests.get(src, headers=headers, timeout=10) ext = src.split('.')[-1].split('?')[0] name = hashlib.md5(src.encode()).hexdigest()[:8] + '.' + ext path = os.path.join(save_dir, name) if not os.path.exists(path): with open(path, 'wb') as f: f.write(r.content) print(f'下载: {name}') except: pass

适配环境

依赖环境:Python 3.7+,需安装requests和beautifulsoup4

使用说明

1.安装Python 3.7+
2.pip install requests beautifulsoup4
3.保存为download_images.py
4.修改脚本中的目标URL
5.python download_images.py 运行
修改url为目标网页地址
支持自定义保存文件夹
自动跳过已下载的图片
可以设置请求头伪装浏览器
部分网站有反爬可能下载失败

常见问题

问:能下载所有图片吗?
答:可以下载img标签中的图片,CSS背景图和懒加载图片可能无法获取

问:下载慢怎么办?
答:可以加多线程,但注意不要给服务器太大压力

Python图片下载爬虫批量素材免费自动化

更多其他