【问题标题】:Download an image from a https URL using python使用 python 从 https URL 下载图像
【发布时间】:2021-10-22 17:19:35
【问题描述】:

我有很多 URL,我需要下载图像文件并将其保存为本地文件。 当我使用我的浏览器时,我可以下载图像,但在我的代码中我得到一个 ConnectionError。

问题是当我使用来自网络的图像的 URL 时,我的代码可以正常工作:

import wget
import requests
local_file = open('local_file.png','wb')
url = "https://ws.addons.om.prod/subom/mg/prod/contracts/contracts1082/C17510266/401032029940E66_photo_type_identity_front_1613034513765.jpg"
resp = requests.get(url, stream=True,verify=True ,timeout=60)
local_file.write(resp.content)
local_file.close()   

【问题讨论】:

  • 那个 URL 给了我 - 无法访问这个站点。

标签: python image url download wget


【解决方案1】:

你有很多 url,你需要寻找线程(即 ThreadPoolExecutor),以便可以同时下载它们。 流程是:

  1. 在列表中获取您的 URL,例如 images_on_a_page
  2. 创建一个下载图片的函数,例如:
def download_image(img_url):
    data_folder=folder_where_need_to_save_images
    try:
        res=requests.get(img_url,allow_redirects = True,headers=headers)
        img_bytes= requests.get(img_url).content # download bytes for a image
        with open(os.path.join(data_folder,img_name),"wb") as img_file:
            img_file.write(img_bytes)
    except Exception as e:
        print(e)
  1. 将列表和函数放入ThreadPoolExecutor
with concurrent.futures.ThreadPoolExecutor() as executor:
        executor.map(download_image,images_on_a_page)

我做了这样的事情来从闪烁下载图像。试试complete program,执行步骤1到7(在笔记本上)。

【讨论】:

  • 非常感谢,它的工作完美
  • 不客气,请接受回复作为答案:)
【解决方案2】:

确保您的链接准确无误并且没有任何错误,这似乎是问题所在。你可以通过this来缩短你的代码:

import requests
f = open('00000001.jpg','wb')
f.write(requests.get('http://www.gunnerkrigg.com//comics/00000001.jpg').content)
f.close()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-25
    • 1970-01-01
    相关资源
    最近更新 更多