python-requests:提取响应内容的头部而不消耗所有内容

发布于 2021-01-29 15:20:31

我想使用python-requests和python-
magic,在不获取其所有内容的情况下测试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

谢谢!

关注者
0
被浏览
45
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    注意
    :在问这个问题时,仅提取主体使用的头流的正确方法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。

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

    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)
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看