python如何从网页上下载图片_python爬虫下载网页图片实战方法

python如何从网页上下载图片_python爬虫下载网页图片实战方法
最新回答
风吹萤火

2026-02-07 16:58:40

用Python从网页下载图片的核心流程可分为获取网页内容、解析提取图片链接、下载保存三步,需借助requests和BeautifulSoup库实现。以下是详细方法及注意事项:

一、核心步骤分解
  1. 获取网页内容

    使用requests.get()发送HTTP请求,需添加headers模拟浏览器行为(避免被反爬)。

    示例代码:

    import requestsheaders = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'}response = requests.get(url, headers=headers, timeout=10)html_content = response.text
  2. 解析HTML提取图片链接

    用BeautifulSoup定位<img>标签,提取src或data-src属性值。

    处理相对路径:通过urljoin()将相对路径与原始域名拼接为完整URL。

    示例代码:

    from bs4 import BeautifulSoupfrom urllib.parse import urljoinsoup = BeautifulSoup(html_content, 'html.parser')img_tags = soup.find_all('img')image_urls = []for img in img_tags: img_url = img.get('src') or img.get('data-src') # 优先取src,若无则取data-src if img_url: full_url = urljoin(url, img_url) # 处理相对路径 image_urls.append(full_url)
  3. 下载并保存图片

    对每个图片URL发送请求,获取二进制数据后写入文件。

    文件命名建议:从URL提取扩展名或生成唯一文件名(如UUID)。

    示例代码:

    import osdef save_image(image_url, output_folder): try: img_data = requests.get(image_url, headers=headers, timeout=10).content filename = os.path.join(output_folder, os.path.basename(urlparse(image_url).path)) with open(filename, 'wb') as f: f.write(img_data) print(f"Saved: {filename}") except Exception as e: print(f"Failed to download {image_url}: {e}")
二、完整实战代码import requestsfrom bs4 import BeautifulSoupimport osfrom urllib.parse import urljoin, urlparsedef download_images_from_url(url, output_folder='downloaded_images'): """从指定URL下载所有图片到本地文件夹""" if not os.path.exists(output_folder): os.makedirs(output_folder) headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' } try: response = requests.get(url, headers=headers, timeout=10) response.raise_for_status() # 检查请求是否成功 html_content = response.text soup = BeautifulSoup(html_content, 'html.parser') img_tags = soup.find_all('img') for img in img_tags: img_url = img.get('src') or img.get('data-src') if img_url: full_url = urljoin(url, img_url) try: img_data = requests.get(full_url, headers=headers, timeout=10).content filename = os.path.join(output_folder, os.path.basename(urlparse(full_url).path)) with open(filename, 'wb') as f: f.write(img_data) print(f"Saved: {filename}") except Exception as e: print(f"Failed to download {full_url}: {e}") except Exception as e: print(f"Error fetching URL {url}: {e}")# 示例调用download_images_from_url('
https://example.com'
)三、常见问题与解决方案
  1. 反爬机制

    问题:网站通过验证User-Agent、Cookies或IP频率限制爬虫。

    解决:

    添加headers模拟浏览器。

    使用requests.Session()维持会话。

    引入代理IP池(如scrapy-proxies)。

  2. 懒加载图片

    问题:图片URL可能藏在data-src或JavaScript动态加载中。

    解决:

    检查data-src属性。

    使用Selenium模拟浏览器渲染(适用于复杂页面)。

  3. 文件命名冲突

    问题:不同URL可能生成相同文件名。

    解决:import uuidfilename = f"{uuid.uuid4().hex}{os.path.splitext(urlparse(img_url).path)[1]}"

  4. 大文件下载优化

    问题:直接下载大图片可能导致内存不足。

    解决:使用流式下载:with requests.get(img_url, headers=headers, stream=True) as r: with open(filename, 'wb') as f: for chunk in r.iter_content(chunk_size=8192): f.write(chunk)

四、扩展工具推荐
  • 异步下载:用aiohttp+asyncio提升速度(适合大量图片)。
  • 图片处理:下载后用Pillow库调整尺寸或格式。
  • 爬虫框架:复杂项目可选用Scrapy(内置图片下载管道)。

通过以上方法,可高效完成网页图片下载任务,同时规避常见陷阱。