网站首页 > 技术文章 正文
在网络爬虫和数据处理中,获取图片内容是常见需求。Python 通过相关库可以便捷地从网络或本地获取图片内容,以下是具体实现方法及注意事项。
一、从网络获取图片内容
1.1 使用 requests 库获取
requests库是获取网络图片的常用工具,通过发送 GET 请求获取图片的字节流(二进制数据)。
import requests
def get_image_from_url(url):
try:
# 设置请求头,模拟浏览器访问
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"
}
# 发送GET请求,获取图片字节流
response = requests.get(url, headers=headers, timeout=10)
# 检查请求是否成功
response.raise_for_status()
# 返回图片字节内容
return response.content
except requests.exceptions.RequestException as e:
print(f"获取图片失败:{e}")
return None
# 示例:获取网络图片
image_url = "https://example.com/image.jpg"
image_content = get_image_from_url(image_url)
if image_content:
print(f"成功获取图片,大小:{len(image_content)}字节")
1.2 处理防盗链和反爬机制
部分网站会通过Referer验证防止图片盗链,此时需在请求头中添加Referer信息。
def get_image_with_referer(url, referer):
try:
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",
"Referer": referer # 添加Referer,模拟从该页面跳转过来的请求
}
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
return response.content
except requests.exceptions.RequestException as e:
print(f"获取图片失败:{e}")
return None
# 示例:带Referer获取图片
image_url = "https://example.com/protected_image.jpg"
referer_url = "
https://example.com/page_contains_image" # 图片所在的页面URL
image_content = get_image_with_referer(image_url, referer_url)
二、从本地文件获取图片内容
若图片已保存在本地,可通过文件操作读取其字节内容。
def get_image_from_local(file_path):
try:
with open(file_path, "rb") as f: # 二进制模式读取
return f.read()
except IOError as e:
print(f"读取本地图片失败:{e}")
return None
# 示例:读取本地图片
local_image_path = "local_image.png"
image_content = get_image_from_local(local_image_path)
if image_content:
print(f"成功读取本地图片,大小:{len(image_content)}字节")
三、图片内容的后续处理
获取图片内容后,可进行保存、显示或进一步处理(如压缩、识别等)。
3.1 保存图片到本地(带弹窗警告)
保存图片时,若存在同名文件,通过弹窗显示警告信息(需使用tkinter库实现图形化提示)。
import os
import tkinter as tk
from tkinter import messagebox
def save_image_with_popup(content, save_path):
# 初始化tkinter(仅用于弹窗)
root = tk.Tk()
root.withdraw() # 隐藏主窗口
# 判断图片是否已存在
if os.path.exists(save_path):
# 弹窗显示警告
messagebox.showwarning("文件已存在", f"警告:{os.path.basename(save_path)} 已存在同名图片,不再写入")
root.destroy()
return False
try:
with open(save_path, "wb") as f: # 二进制模式写入
f.write(content)
print(f"图片已保存至:{save_path}")
root.destroy()
return True
except IOError as e:
messagebox.showerror("保存失败", f"图片保存失败:{str(e)}")
root.destroy()
return False
# 示例:带弹窗警告保存图片
if image_content:
save_image_with_popup(image_content, "downloaded_image.jpg")
3.2 使用 PIL 库显示图片
需安装Pillow库(pip install pillow),可直接在程序中显示图片或进行处理。
from PIL import Image
from io import BytesIO
def show_image(content):
try:
# 将字节内容转换为图片对象
image = Image.open(BytesIO(content))
image.show() # 调用系统默认图片查看器显示
except Exception as e:
print(f"显示图片失败:{e}")
# 示例:显示获取的图片
if image_content:
show_image(image_content)
四、注意事项
- 弹窗依赖:tkinter是 Python 标准库,无需额外安装,但在部分服务器环境(如无图形界面的 Linux)中可能无法显示弹窗,此时可退回控制台提示。
- 合规性:获取网络图片时需遵守 robots 协议和网站版权声明,避免非法爬取。
- 异常处理:网络请求和文件操作可能出现各种异常,需通过try-except确保程序稳定性。
通过上述方法,可实现图片的获取、保存(带同名文件弹窗警告)和显示,满足不同场景下的图片处理需求。
猜你喜欢
- 2025-08-01 利用Python图像搜索:给你爬的美女图建一个搜索引擎
- 2025-08-01 Python学不会来打我(34)python函数爬取百度图片_附源码
- 2025-08-01 手把手带你用python爬取小姐姐私房照,准备好你的纸
- 2025-08-01 还在手动保存图片?Python 爬虫 3 步搞定整站图片,附避坑指南
- 08-03Python列表方法append和extend的区别
- 08-03Python列表集合操作介绍?
- 08-03python数据类型之列表、字典、元组、集合及操作
- 08-03Python学不会来打我(11)列表list详解:用法、场景与类型转换
- 08-03Python骚操作从列表推导和生成器表达式开始
- 08-03Python中的列表详解及示例
- 08-03Python自动化办公应用学习笔记20—列表排序、列表推导式
- 08-03python入门012:复制列表
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)