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

相关推荐
m0_7436239212 小时前
React 自定义 Hook 的命名规范与调用规则详解
jvm·数据库·python
拾贰_C13 小时前
【Google | Gemini | API | POST】怎么使用Google 的Gemini API (原生版)
开发语言·lua
FreakStudio13 小时前
无硬件学LVGL—定时器篇:基于Web模拟器+MicroPython速通GUI开发
python·单片机·嵌入式·大学生·面向对象·并行计算·电子diy·电子计算机
gCode Teacher 格码致知13 小时前
Python提高:pytest的简单案例-由Deepseek产生
python·pytest
t***54413 小时前
如何在Dev-C++中选择Clang编译器
开发语言·c++
橙子1991101613 小时前
Java 基础相关
java·开发语言
不要秃头的小孩13 小时前
力扣刷题——509. 斐波那契数
python·算法·leetcode·动态规划
科雷软件测试14 小时前
使用python+Midscene.js AI驱动打造企业级WEB自动化解决方案
前端·javascript·python
星越华夏14 小时前
python——三角函数用法
开发语言·python