Python 如何使用url下载具有名称的图像?

Python 如何使用url下载具有名称的图像?,python,python-3.x,image,python-requests,Python,Python 3.x,Image,Python Requests,我想用python下载图片。我怎样才能下载它?我可以尝试谷歌提供的所有订单,但没有一个代码不适用于这种类型的url 我尝试过以下代码: import requests # to get image from the web import shutil # to save it locally ## Set up the image URL and filename image_url = "https://graph.facebook.com/264520706917918/pict

我想用python下载图片。我怎样才能下载它?我可以尝试谷歌提供的所有订单,但没有一个代码不适用于这种类型的url

我尝试过以下代码:

import requests # to get image from the web
import shutil # to save it locally

## Set up the image URL and filename
image_url = "https://graph.facebook.com/264520706917918/picture"
filename = image_url.split("/")[-1]

# Open the url image, set stream to True, this will return the stream content.
r = requests.get(image_url, stream = True)

# Check if the image was retrieved successfully
if r.status_code == 200:
    # Set decode_content value to True, otherwise the downloaded image file's size will be zero.
    r.raw.decode_content = True

    # Open a local file with wb ( write binary ) permission.
    with open(filename,'wb') as f:
        shutil.copyfileobj(r.raw, f)

    print('Image sucessfully Downloaded: ',filename)
else:
    print('Image Couldn\'t be retreived')
还有这些代码:

# import wget

# # Set up the image URL
# image_url = "https://graph.facebook.com/264520706917918/picture"

# # Use wget download method to download specified image url.
# image_filename = wget.download(image_url)

# print('Image Successfully Downloaded: ', image_filename)
尝试改变

r = requests.get(image_url, stream = True)


请包括您尝试过的代码。可能是一个奇怪的问题,但您尝试过谷歌搜索吗?我发现,,,我可以继续,我已经尝试过了,但没有工作,只是下载了未知格式的图片,我无法打开它
r = requests.get(image_url, stream = True).raw