如何使用Urllib或Shutil将图像下载到特定的本地目录?
我使用slutil从URL下载图像,它可以正常工作,但它在项目目录上下载了图像。是否可以指定目录以使程序将其保存在那里?
我在Stackoverflow上搜索了一个解决方案,但仅使用Urllib urlretrieve找到了一个解决方案,该解决方案与我要做的事情并不相关。谢谢
import requests
import shutil
import os
import urllib.request
url = "https://www.lamborghini.com/sites/it-en/files/DAM/lamborghini/facelift_2019/homepage/families-gallery/2022/04_12/family_chooser_tecnica_m.png"
file_name = input("save image as :")
file_name += ".jpg"
res = requests.get(url, stream = True)
if res.ok:
with open(file_name,"wb") as f:
shutil.copyfileobj(res.raw,f)
print("image succesfully downloaded ", file_name)
else:
print("Download failed: status code {}\n{}".format(res.status_code, res.text))
或使用Urllib
f = open("sadasd.png", "wb")
f.write(urllib.request.urlopen(r"https://www.lamborghini.com/sites/it-en/files/DAM/lamborghini/facelift_2019/homepage/families-gallery/2022/04_12/family_chooser_tecnica_m.png").read())
f.close()
I used shutil to download an image from an URL and it works fine but it downloads the images on the project directory. Is it possible to specify a directory so that the program saves it there?
I searched for a solution on StackOverflow but only found a solution using urllib urlretrieve which does not really relate to what I am trying to do. Thank you
import requests
import shutil
import os
import urllib.request
url = "https://www.lamborghini.com/sites/it-en/files/DAM/lamborghini/facelift_2019/homepage/families-gallery/2022/04_12/family_chooser_tecnica_m.png"
file_name = input("save image as :")
file_name += ".jpg"
res = requests.get(url, stream = True)
if res.ok:
with open(file_name,"wb") as f:
shutil.copyfileobj(res.raw,f)
print("image succesfully downloaded ", file_name)
else:
print("Download failed: status code {}\n{}".format(res.status_code, res.text))
or using urllib
f = open("sadasd.png", "wb")
f.write(urllib.request.urlopen(r"https://www.lamborghini.com/sites/it-en/files/DAM/lamborghini/facelift_2019/homepage/families-gallery/2022/04_12/family_chooser_tecnica_m.png").read())
f.close()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我找到了一个简单的解决方案。因此,我将代码更改为仅使用Urllib。我缺少的是目标路径末端的前向斜线,即C:用户\ User \ Pictures \ test/。
为了添加另一个信息,您可以在“代码块”中看到的,使用第二个参数作为要保存的位置。
导入Urllib.Request
I found a simpler solution. So I changed my code to use only Urllib. What I was missing was the forward slash at the end of the destination path which is C:users\user\Pictures\test/.
To add another piece of information as you can see in the code block urlretrieve uses the second argument as a location that you want to save.
import urllib.request