在Python网络申请中级篇中,咱们理解了如何通过Requests库发送带参数的申请,解决Cookies,应用Session对象,以及设置申请头。在本文中,咱们将进一步深刻学习Requests库的高级性能,包含解决重定向,设置超时,解决大文件以及谬误和异样解决。

一、解决重定向

默认状况下,Requests会主动解决重定向。咱们能够通过响应对象的history属性查看重定向历史。如果咱们不想让Requests主动解决重定向,能够通过allow_redirects选项来禁止重定向。

import requestsresponse = requests.get('http://github.com', allow_redirects=False)print(response.status_code)print(response.history)

二、设置超时

咱们能够通过timeout选项为申请设置超时工夫。超时工夫能够设置为一个浮点数,示意申请的最长工夫,单位为秒。

import requeststry:    response = requests.get('http://github.com', timeout=0.001)except requests.exceptions.Timeout:    print('The request timed out')

三、解决大文件

当咱们须要下载大文件时,咱们应该防止一次性读取整个文件到内存。咱们能够通过流(stream)来解决大文件。

import requestsresponse = requests.get('http://example.com/big_file', stream=True)with open('big_file', 'wb') as fd:    for chunk in response.iter_content(chunk_size=128):        fd.write(chunk)

这段代码将会分块读取大文件,每块的大小为128字节,并将每块写入到本地的big_file文件中。

四、谬误和异样解决

Requests库提供了一套残缺的异样体系,能够解决各种谬误。例如,咱们能够捕捉RequestException异样,这是所有Requests异样的基类。

import requestsfrom requests.exceptions import RequestExceptiontry:    response = requests.get('http://example.com')except RequestException as e:    print('There was an ambiguous exception that occurred while handling your request.', e)

深度了解Requests库,能够让咱们在解决网络申请时更加得心应手。不管你是要进行爬虫开发,还是API测试,Requests库都是你的得力工具。