Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何测试网页是否为图像_Python_List_Python 3.x_Urllib - Fatal编程技术网

Python 如何测试网页是否为图像

Python 如何测试网页是否为图像,python,list,python-3.x,urllib,Python,List,Python 3.x,Urllib,很抱歉,标题不是很清楚,基本上我有一个完整的url系列的列表,目的是下载那些图片。有没有办法检查网页是否是图像,这样我就可以跳过那些不是图像的 提前感谢您可以使用mimetypes 这将返回“png”没有可靠的方法。但在你的情况下,你可以找到一个“足够好”的解决方案 如果文件扩展名出现在url中,您可以查看它,例如,.png,.jpg可能表示图像: >>> import os >>> name = url2filename('http://example.co

很抱歉,标题不是很清楚,基本上我有一个完整的url系列的列表,目的是下载那些图片。有没有办法检查网页是否是图像,这样我就可以跳过那些不是图像的


提前感谢

您可以使用
mimetypes


这将返回“png”

没有可靠的方法。但在你的情况下,你可以找到一个“足够好”的解决方案

如果文件扩展名出现在url中,您可以查看它,例如,
.png
.jpg
可能表示图像:

>>> import os
>>> name = url2filename('http://example.com/a.png?q=1')
>>> os.path.splitext(name)[1]
'.png'
>>> import mimetypes
>>> mimetypes.guess_type(name)[0]
'image/png'
在哪里

您可以检查
内容类型
http头:

>>> import urllib.request
>>> r = urllib.request.urlopen(url) # make HTTP GET request, read headers
>>> r.headers.get_content_type()
'image/png'
>>> r.headers.get_content_maintype()
'image'
>>> r.headers.get_content_subtype()
'png'
您可以在http正文的最开始处检查指示图像文件的幻数,例如,或:

,你可以使用:

您可以使用模块。发出head请求并检查内容类型。Head请求不会下载响应正文

import requests
response = requests.head(url)
print response.headers.get('content-type')

类似的问题:你可以在Python3上使用它(这个问题有标记)如果你修复了导入,你可以让它工作。此外,还不清楚为什么要在此处猜测文件扩展名。内容类型本身是清晰的:它甚至可能包含“image”一词(您可以按中所示提取它)
>>> prefix = r.read(8)
>>> prefix # .png image
b'\x89PNG\r\n\x1a\n'
>>> import imghdr
>>> imghdr.what(None, b'\x89PNG\r\n\x1a\n')
'png'
import requests
response = requests.head(url)
print response.headers.get('content-type')