python 获取网页链接图片

python 获取 网页图片

在Python中,可以使用requests库获取网页内容,再使用BeautifulSoup解析网页,提取图片链接,最后保存图片到本地。以下是一个简单的例子:

import requests

from bs4 import BeautifulSoup

import os

网页URL

url = 'http://example.com'

发送HTTP请求

response = requests.get(url)

检查请求是否成功

if response.status_code == 200:

解析网页内容

soup = BeautifulSoup(response.text, 'html.parser')

复制代码
# 找到所有的img标签
images = soup.find_all('img')

# 循环遍历图片链接并下载保存
for img in images:
    # 获取图片链接
    img_url = img.get('src')
    
    # 使用requests下载图片
    img_response = requests.get(img_url)
    
    # 获取图片文件名
    filename = os.path.basename(img_url)
    
    # 保存图片到本地
    with open(filename, 'wb') as f:
        f.write(img_response.content)
        print(f'图片 {filename} 已保存。')

else:

print('网页请求失败')

确保在运行代码前已经安装了requests和beautifulsoup4库:

pip install requests beautifulsoup4

相关推荐
曲幽9 小时前
数据库实战:FastAPI + SQLAlchemy 2.0 + Alembic 从零搭建,踩坑实录
python·fastapi·web·sqlalchemy·db·asyncio·alembic
用户83562907805114 小时前
Python 实现 PowerPoint 形状动画设置
后端·python
ponponon15 小时前
时代的眼泪,nameko 和 eventlet 停止维护后的项目自救,升级和替代之路
python
Flittly15 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(5)Skills (技能加载)
python·agent
敏编程15 小时前
一天一个Python库:pyarrow - 大规模数据处理的利器
python
Flittly17 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(4)Subagents (子智能体)
python·agent
明月_清风1 天前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python
明月_清风1 天前
打破“死亡环联”:深挖 Python 分代回收与垃圾回收(GC)机制
后端·python
ZhengEnCi2 天前
08c. 检索算法与策略-混合检索
后端·python·算法
明月_清风2 天前
Python 内存手术刀:sys.getrefcount 与引用计数的生死时速
后端·python