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

相关推荐
2601_9516437717 分钟前
Python第一,Java跌出前三,C语言杀回来了
java·c语言·python·编程语言排行·技术趋势
小小编程路17 分钟前
C++ 异常 完整讲解
开发语言·c++
AI科技星1 小时前
数术工坊 · 第四卷 橡皮泥江湖(拓扑学)【完整定稿】
c语言·开发语言·汇编·electron·概率论·拓扑学
张忠琳1 小时前
【Go 1.26.4】Golang Select 深度解析
开发语言·后端·golang
AC赳赳老秦2 小时前
OpenClaw+Power Apps 实战:自动生成 Power Apps 应用、连接 Excel 数据源
大数据·开发语言·python·serverless·excel·deepseek·openclaw
提笔了无痕2 小时前
如何用Go实现整套RAG流程
开发语言·后端·golang
(Charon)3 小时前
【C++ 面试高频基础:指针、引用、const、static、new/delete 总结】
java·开发语言
2601_961875243 小时前
法考考试时间安排及科目|时间表|资料已整理
开发语言·c#·inverted-index·suffix-tree·sstable·r-tree·lsm-tree
AI科技星3 小时前
数术工坊第八卷:算力革命
c语言·开发语言·网络·量子计算·agi
geovindu3 小时前
go: Generators Pattern
开发语言·后端·设计模式·golang·生成器模式