遇事不决,可问春风,春风不语,谨遵本心|

布都御魂

园龄:3年9个月粉丝:2关注:1

下载图片

复制代码
把图片下载到本地
async def fetch_and_save_image(img_urls, title):
    try:
        # 获取代理,并确保它是正确的格式
        if not proxy:
            print("代理配置错误,请检查 redis_ip.ip() 的返回值。")
            return
        async with httpx.AsyncClient(proxies=proxy, timeout=20) as client:
            response = await client.get(url=img_urls)
            if response.status_code == 200:
                # 获取图片内容
                image_content = response.content
                # 定义文件名,确保文件名安全
                file_path = f"{title}.jpg"  # 使用 .jpg 后缀
                # 保存图片到本地
                with open(file_path, 'wb') as f:
                    f.write(image_content)
                print(f"图片已保存为: {file_path}")
            else:
                print(f"无法下载图片,状态码: {response.status_code}")
    except httpx.RequestError as e:
        print(f"请求失败:{e}")
    except FileNotFoundError:
        print("文件路径错误或无法创建文件。")
    except PermissionError:
        print("没有权限写入文件。")
    except Exception as e:
        print(f"发生未知错误:{e}")
img_urls='http://images.bookuu.com/book_t/31/18/08/31180800-1.jpg'
title='从零开始学外汇交易'
# 使用 asyncio 的事件循环来运行异步函数。
loop = asyncio.get_event_loop()
loop.run_until_complete(fetch_and_save_image(img_urls, title))
复制代码

 

本文作者:布都御魂

本文链接:https://www.cnblogs.com/wolvies/p/15407146.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   布都御魂  阅读(140)  评论(0编辑  收藏  举报
   
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起