python 爬取网站图片的小demo

python 复制代码
# demo.py
# 首先引入各个模块
import os
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin

def download_static_resources(url, output_dir="downloads"):
    # 创建输出目录
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    # 设置请求头,模拟浏览器访问
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36"
    }
    
    try:
        # 发送请求获取网页内容
        response = requests.get(url, headers=headers)
        if response.status_code != 200:
            print("无法访问页面,请检查链接是否有效!")
            return
        
        # 使用 BeautifulSoup 解析 HTML 内容
        soup = BeautifulSoup(response.text, 'html.parser')
        
        # 查找所有图片标签
        img_tags = soup.find_all("img")
        print(f"找到 {len(img_tags)} 张图片")
        
        for img in img_tags:
            # 获取图片的 src 属性
            img_url = img.get("src") or img.get("data-src")  # 有些图片可能使用 data-src
            if not img_url:
                continue
            
            # 将相对路径转换为绝对路径
            img_url = urljoin(url, img_url)
            
            # 下载图片
            try:
                img_response = requests.get(img_url, headers=headers)
                if img_response.status_code == 200:
                    # 提取文件名
                    img_name = os.path.basename(img_url.split("?")[0])  # 去掉查询参数
                    img_path = os.path.join(output_dir, img_name)
                    
                    # 保存图片到本地
                    with open(img_path, "wb") as img_file:
                        img_file.write(img_response.content)
                    print(f"已下载:{img_name}")
                else:
                    print(f"无法下载图片:{img_url}")
            except Exception as e:
                print(f"下载图片时出错:{e}")
    
    except Exception as e:
        print("发生错误:", e)

# 测试代码
if __name__ == "__main__":
    print("欢迎使用网页图片下载器!")
    print("请输入要下载图片的网页地址,按回车确认。")
    target_url = input("网页地址:")
    print("开始下载...")
    download_static_resources(target_url)
    print("\n下载完成!按回车键退出...")
    input()

使用:先安装必要的库,

bash 复制代码
pip install requests beautifulsoup4

运行:

bash 复制代码
python "/demo.py"

我们可以使用 PyInstaller 来将这个 Python 脚本打包成 exe 文件。以下是具体步骤:

bash 复制代码
pip install pyinstaller
bash 复制代码
pyinstaller --onefile --icon=download.ico demo.py


- --onefile : 打包成单个exe文件
- --icon : 添加图标(可选,需要准备一个.ico文件)
相关推荐
默_笙2 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
小羊没烦恼!2 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
qq_426003962 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫2 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技3 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读3 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时3 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
C语言小火车3 天前
C/C++ 为什么需要编译器?
开发语言·c++
奇思妙想聪明勤奋的小羊3 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd1233 天前
2026年第38周GitHub趋势周报
python·科技·github