【问题标题】:How to check file type for an image stored as url?如何检查存储为 url 的图像的文件类型?
【发布时间】:2020-10-16 07:36:32
【问题描述】:

我有一个或多或少看起来像这样的网址列表:

'https://myurl.com/images/avatars/cb55-f14b-455d1-9ac4w20190416075520341'

我正在尝试验证 url 后面的图像并检查它具有什么图像类型(png、jpeg 或其他)并将图像类型写回新的数据框列 imgType。

到目前为止我的代码

import pandas as pd
import requests

df = pd.read_csv('/path/to/allLogo.csv')
urls = df.T.values.tolist()[4]

for x in urls:
#i'm stuck here... as the content doesn't seem to give me image type.
s=requests.get(url, verify=False).content


df["imgType"] =
df.to_csv('mypath/output.csv')

有人可以帮我解决这个问题吗?提前谢谢

【问题讨论】:

  • 这个问题取决于网站如何在屏幕上呈现图像(是否通过 iFrame、img 标签等等等)。如果您可以发布一个有效的 URL,它将帮助我们帮助您。

标签: python pandas python-requests


【解决方案1】:

一种可能性是检查'Content-Type' 的响应标头 - 但它取决于服务器将哪些标头发送回客户端(不知道真正的 URL 很难分辨):

import requests

url = 'https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png'

response = requests.get(url)

# uncomment this to print all response headers:
# print(response.headers)

print(response.headers['Content-Type'])

打印:

image/png

【讨论】:

    【解决方案2】:

    检查图像类型(png、jpeg 或其他)

    如果您设法将其下载到磁盘(文件)或内存(作为字节 - requests' 响应的 .content),那么您可以利用 python 内置模块 imghdr,如下方式:

    import imghdr
    imgtype = imghdr.what("path/to/image.png")  # testing file on disk
    

    import requests
    r = requests.get("url_of_image")
    imgtype = imghdr.what(h=r.content)  # testing
    

    请记住,imghdr 确实可以识别有限的图像文件格式集(请参阅链接文档),但是如果您只对检测 pngjpeg 与其他比较感兴趣,它就足够了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-02
      • 1970-01-01
      相关资源
      最近更新 更多