如何在 url 中找到文件类型不明显的文件类型 Python
How do you find the filetype of an image in a url with nonobvious filetype in Python
像 googleusercontent 这样的某些 CDN 不会(显然)在它们的 url 中对图像的文件名进行编码,因此您不能像这里的其他答案所建议的那样简单地使用字符串操作来获取文件类型。知道这个,怎么知道那个
是 gif 而
是一个 jpg
根据对此 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 中获取图像类型
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:
如果你真的只关心 link 的文件类型而不是文件本身,你可以使用 head
方法而不是请求模块的 get
方法。更快:
headers = requests.head(url).headers
file_type =headers.get('Content-Type', "nope/nope").split("/")[1]
像 googleusercontent 这样的某些 CDN 不会(显然)在它们的 url 中对图像的文件名进行编码,因此您不能像这里的其他答案所建议的那样简单地使用字符串操作来获取文件类型。知道这个,怎么知道那个
是 gif 而
是一个 jpg
根据对此 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 中获取图像类型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:
如果你真的只关心 link 的文件类型而不是文件本身,你可以使用 head
方法而不是请求模块的 get
方法。更快:
headers = requests.head(url).headers
file_type =headers.get('Content-Type', "nope/nope").split("/")[1]