使用python请求和python魔术,我想测试一个web资源的mime类型,而不需要获取它的所有内容(特别是如果这个资源碰巧是例如。ogg文件或PDF文件)。根据结果,我可能会决定将其全部获取。但是,在测试mime类型之后调用text方法只会返回尚未使用的内容。如何在不使用响应内容的情况下测试mime类型?
下面是我当前的代码。
import requests
import magic
r = requests.get("http://www.december.com/html/demo/hello.html", prefetch=False)
mime = magic.from_buffer(r.iter_content(256).next(), mime=True)
if mime == "text/html":
print(r.text) # I'd like r.text to give me the entire response content谢谢!
发布于 2012-11-02 23:14:06
注意:在提出这个问题的时候,正确的方法是使用prefetch=False来获取正文的头文件流。该选项后来被重命名为stream,并且布尔值被反转,因此您需要stream=True。
最初的答案如下。
一旦您使用了iter_content(),您就必须继续使用它;.text在幕后(通过.content)间接使用相同的接口。
换句话说,通过使用iter_content(),您必须手动完成.text所做的工作:
from requests.compat import chardet
r = requests.get("http://www.december.com/html/demo/hello.html", prefetch=False)
peek = r.iter_content(256).next()
mime = magic.from_buffer(peek, mime=True)
if mime == "text/html":
contents = peek + b''.join(r.iter_content(10 * 1024))
encoding = r.encoding
if encoding is None:
# detect encoding
encoding = chardet.detect(contents)['encoding']
try:
textcontent = str(contents, encoding, errors='replace')
except (LookupError, TypeError):
textcontent = str(contents, errors='replace')
print(textcontent)假设您使用的是Python 3。
另一种方法是发出两个请求:
r = requests.get("http://www.december.com/html/demo/hello.html", prefetch=False)
mime = magic.from_buffer(r.iter_content(256).next(), mime=True)
if mime == "text/html":
print(r.requests.get("http://www.december.com/html/demo/hello.html").text)Python 2版本:
r = requests.get("http://www.december.com/html/demo/hello.html", prefetch=False)
peek = r.iter_content(256).next()
mime = magic.from_buffer(peek, mime=True)
if mime == "text/html":
contents = peek + ''.join(r.iter_content(10 * 1024))
encoding = r.encoding
if encoding is None:
# detect encoding
encoding = chardet.detect(contents)['encoding']
try:
textcontent = unicode(contents, encoding, errors='replace')
except (LookupError, TypeError):
textcontent = unicode(contents, errors='replace')
print(textcontent)发布于 2012-11-03 00:03:08
如果“content-type”足够,您可以发出HTTP“Head”请求,而不是“Get”,以仅接收HTTP标头。
import requests
url = 'http://www.december.com/html/demo/hello.html'
response = requests.head(url)
print response.headers['content-type']https://stackoverflow.com/questions/13197854
复制相似问题