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

相关推荐
小小测试开发10 小时前
安装 Python 3.10+
开发语言·人工智能·python
梦想不只是梦与想11 小时前
Python 中的装饰器
python·装饰器
我叫唧唧波11 小时前
Python+AI 全栈学习笔记
人工智能·python·学习
AAA大运重卡何师傅(专跑国道)12 小时前
【无标题】
开发语言·c#
copyer_xyf12 小时前
Python 异常处理
前端·后端·python
XBodhi.12 小时前
Visual Studio C++ 语法错误: 缺少“;”(在“return”的前面)
开发语言·c++·visual studio
麻雀飞吧12 小时前
期货多合约策略目标持仓怎么更新才不乱
python·区块链
Cthy_hy12 小时前
拓扑排序超详解:原理 + Kahn 贪心算法
python·算法·贪心算法
LSssT.13 小时前
【01】Python 机器学习
开发语言·python
为爱停留13 小时前
给智能体装上「刹车」:中断(Interrupts)与人工审批全解析
python