【问题标题】:How do you find the filetype of an image in a url with nonobvious filetype in Python如何在 Python 中找到具有非明显文件类型的 url 中的图像的文件类型
【发布时间】:2021-06-29 01:15:10
【问题描述】:

像 googleusercontent 这样的某些 CDN 不会(显然)在其 url 中对图像的文件名进行编码,因此您无法像这里的其他答案所建议的那样简单地使用字符串操作来获取文件类型。知道这一点,怎么能说出来

https://lh3.googleusercontent.com/pw/AM-JKLURvu-Ro2N3c1vm1PTM3a7Ae5nG3LNWynuKNEeFNBMwH_uWLQJe0q0HmaOzKC0k0gRba10SbonLaheGcNpxROnCenf1YJnzDC3jL-N9fTtZ7u0q5Z-3iURXtrt4GlyeEI3t4KWxprFDqFWRO29sJc8=w440-h248-no

是一个gif,而

https://lh3.googleusercontent.com/pw/AM-JKLXk2WxafqHOi0ZrETUh2vUNkiLyYW1jRmAQsHBmYyVP7Le-KBCSVASCgO2C6_3QbW3LcLYOV_8OefPafyz2i4g8nqpw8xZnIhzDdemd5dFPS5A7dVAGQWx9DIy5aYOGuh06hTrmfhF9mZmITjjTwuc=w1200-h600-no

是一个jpg

【问题讨论】:

  • 至少下载文件的前几个字节。大多数格式都以“魔术字节”序列开头,以识别“GIF”或“JFIF”等格式。

标签: python python-3.x file url file-type


【解决方案1】:

根据对此question 的回复,您可以尝试:

import requests
from PIL import Image       # pillow package
from io import BytesIO

url = "your link"

image = Image.open( BytesIO( requests.get( url ).content))
file_type = image.format

不过,这需要下载整个文件。如果您希望批量执行此操作,您可能需要探索上面评论中提到“魔术字节”的选项...

编辑: 您还可以尝试从对您的 url 的响应的标题中获取图像类型:

headers = requests.get(url).headers
file_type =headers.get('Content-Type', "nope/nope").split("/")[1]
# Will print 'nope' if 'Content-Type' header isn't found
print(file_type)
# Will print 'gif' or 'jpeg' for your listed urls

编辑 2: 如果你真的只关心链接的文件类型而不是文件本身,你可以使用head 方法而不是请求模块的get 方法。更快:

headers = requests.head(url).headers
file_type =headers.get('Content-Type', "nope/nope").split("/")[1]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-21
    • 2022-12-01
    相关资源
    最近更新 更多