Python下载图片的时候,怎么知道图片的名称和格式?

例如:https://webquoteklinepic.eastmoney.com/GetPic.aspx?nid=0.000651&imageType=k&token=28dfeb41d35cc81d84b4664d7c23c49f&at=1

能下载,但是保存图片的时候,怎么保存成原文件名呢?在网页手动保存的时候,图片名称是GetPic.png,看上去好像是图片URL里的GetPic + png

1、保存(或者下载)的时候怎么得到原文件名?
2、怎么知道文件格式(jpg,png)?

img_url = 'https://webquoteklinepic.eastmoney.com/GetPic.aspx?nid=0.000651&imageType=k&token=28dfeb41d35cc81d84b4664d7c23c49f&at=1'
pic = requests.get(img_url)
pic_name = item['url'].split('/'[-1].replace('html','jpg').replace('htm','jpg').replace('shtml','jpg') #目前用的方法
with open(file_path + '\\' + pic_name,'wb') as f:
    f.write(pic.content)
阅读 3.9k
1 个回答

这个链接的 response header 是这样的,

HTTP/1.1 200 OK
Connection: close
Content-Type: image/png
Content-Length: 8896

里面有格式。

文档 貌似可以用 pic.headers['Content-Type'] 拿到。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题