温馨提示×

怎么用Python实现轻松下载照片

小亿
84
2023-10-30 13:23:02
栏目: 编程语言

要使用Python下载照片,你可以使用以下步骤:

  1. 导入所需的模块:

    import requests
    
  2. 指定要下载的图片的URL:

    image_url = "https://example.com/image.jpg"
    
  3. 发送GET请求以获取图片的二进制数据:

    response = requests.get(image_url)
    
  4. 将响应的内容写入文件:

    with open("image.jpg", "wb") as file:
        file.write(response.content)
    

完整代码如下所示:

import requests

image_url = "https://example.com/image.jpg"
response = requests.get(image_url)

with open("image.jpg", "wb") as file:
    file.write(response.content)

在这个例子中,我们使用了requests模块来发送GET请求并获取图片的二进制数据。然后,我们使用open函数以二进制写入模式打开一个文件,并将响应的内容写入文件中。你可以根据自己的需要更改文件名和路径。

0