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

相关推荐
Thneonl10 小时前
Celery 生产踩坑:1000 任务积压与 acks_late 双重执行
后端·python
清桔10 小时前
模型的调用
python
小小张说故事10 小时前
Python 多线程为什么跑不快?asyncio 入门指南:异步并发从零上手
后端·python
10年前端老司机10 小时前
干货分享|企业智能知识库 Rerank 重排序落地实践与踩坑总结
python·aigc·agent
天天被压力10 小时前
【Python 量化取数指南 #13】Python 把行情落库:sqlite 一键存,回测随用随取
java·人工智能·python
天天被压力10 小时前
【Python 量化取数指南 #14】Python 清洗行情数据:复权停牌对齐,回测不翻车
java·人工智能·python
Python私教10 小时前
Python环境配置:conda+PyCharm+换源,附6个坑
人工智能·python·pycharm
databook10 小时前
检测数据异常值的五种统计技术
python·数据挖掘·数据分析
小小张说故事10 小时前
Selenium 装驱动太麻烦?Playwright 入门指南:Python 网页自动化新标准
python
海宇数科10 小时前
Python数据工程:利用海宇车型识别精准优化车险理赔合规体验
人工智能·python