首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python-requests:获取响应内容的头部,而不使用所有内容

python-requests:获取响应内容的头部,而不使用所有内容
EN

Stack Overflow用户
提问于 2012-11-02 23:04:42
回答 2查看 3.3K关注 0票数 4

使用python请求和python魔术,我想测试一个web资源的mime类型,而不需要获取它的所有内容(特别是如果这个资源碰巧是例如。ogg文件或PDF文件)。根据结果,我可能会决定将其全部获取。但是,在测试mime类型之后调用text方法只会返回尚未使用的内容。如何在不使用响应内容的情况下测试mime类型?

下面是我当前的代码。

代码语言:javascript
复制
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

谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-11-02 23:14:06

注意:在提出这个问题的时候,正确的方法是使用prefetch=False来获取正文的头文件流。该选项后来被重命名为stream,并且布尔值被反转,因此您需要stream=True

最初的答案如下。

一旦您使用了iter_content(),您就必须继续使用它;.text在幕后(通过.content)间接使用相同的接口。

换句话说,通过使用iter_content(),您必须手动完成.text所做的工作:

代码语言:javascript
复制
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。

另一种方法是发出两个请求:

代码语言:javascript
复制
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版本:

代码语言:javascript
复制
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)
票数 4
EN

Stack Overflow用户

发布于 2012-11-03 00:03:08

如果“content-type”足够,您可以发出HTTP“Head”请求,而不是“Get”,以仅接收HTTP标头。

代码语言:javascript
复制
import requests

url = 'http://www.december.com/html/demo/hello.html'
response = requests.head(url)
print response.headers['content-type']
票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13197854

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档