gpt4 book ai didi

Python从HTTPS aspx下载图像

转载 作者:太空宇宙 更新时间:2023-11-03 14:14:14 25 4
gpt4 key购买 nike

我正在尝试从 NASS Case Viewer 下载一些图像。一个案例的例子是

本例的图像查看器链接为

这可能是不可见的,我猜是因为 https。然而,这只是正面第二张图片。

图像的实际链接是(或者应该是?)

这将简单地下载 aspx 二进制文件。

我的问题是我不知道如何将这些二进制文件存储到正确的 jpg 文件中。

我尝试过的代码示例是

import requests 
test_image = "https://www-nass.nhtsa.dot.gov/nass/cds/GetBinary.aspx?Image&ImageID=497001669&CaseID=149006692&Version=1"
pull_image = requests.get(test_image)

with open("test_image.jpg", "wb+") as myfile:
myfile.write(str.encode(pull_image.text))

但这不会产生正确的 jpg 文件。我还检查了 pull_image.raw.read() 并发现它是空的。

这里可能出现什么问题?我的网址不正确吗?我使用 Beautifulsoup 将这些 URL 放在一起,并通过检查几个页面的 HTML 代码来检查它们。

我是否错误地保存了二进制文件?

最佳答案

.text 将响应内容解码为字符串,因此您的图像文件将被损坏。
相反,您应该使用 .content它保存二进制响应内容。

import requests 

test_image = "https://www-nass.nhtsa.dot.gov/nass/cds/GetBinary.aspx?Image&ImageID=497001669&CaseID=149006692&Version=1"
pull_image = requests.get(test_image)

with open("test_image.jpg", "wb+") as myfile:
myfile.write(pull_image.content)

.raw.read() 也返回字节,但为了使用它,您必须将 stream 参数设置为 True

pull_image = requests.get(test_image, stream=True)
with open("test_image.jpg", "wb+") as myfile:
myfile.write(pull_image.raw.read())

关于Python从HTTPS aspx下载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48308973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com