01.Requests库学习

本文介绍了Python的HTTP库Requests的基本用法及高级特性,包括安装、常用方法如GET、POST等,以及如何处理响应数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Requests库学习

Requests介绍

requests库是一个Python的HTTP库,可以进行丰富的Http操作。

Requests安装

pip install requests

常用方法介绍

requests.request(method, url, **args)构造一个请求,是requests其他库的基础方法,其他请求方法都是在request方法之上构造的。

method 参数包含GET、 POST、 HEAD、 PUT、 PATCH、 DELETE
url 参数是URL
args是请求的配置参数包含如下:

params参数拼接到GET请求的url后的参数 格式使用dict类型

payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
r = requests.request('GET','http://httpbin.org/get', params=payload)
print(r.url)
'''
http://httpbin.org/get?key1=value1&key2=value2&key2=value3
'''

headers 请求头信息,dict类型

url = 'https://api.github.com/some/endpoint'
headers = {'user-agent': 'my-app/0.0.1'}
r = requests.request('GET',url, headers=headers)

data配合POST请求,data传递请求体参数

payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", data=payload)

json参数,配合POST请求发送请求体,会转换成JSON格式数据

url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
r = requests.post(url, json=payload)

files参数,上传文件

url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)

cookies参数,设置请求cookies

url = 'http://httpbin.org/cookies'
cookies = dict(cookies_are='working')
r = requests.get(url, cookies=cookies)

allow_redirects参数, 是否开启重定向

r = requests.get('http://github.com', allow_redirects=False)#不允许重定向

timeout参数,设置超时时间,timeout 仅对连接过程有效

requests.get('http://github.com', timeout=0.001)

proxies设置代理

pxs = {'http':'http://user:pass@xxx',
        'https':'xxxxx'}
r = requests.request("GET",url, proxies=pxs)

auth : 元组,支持HTTP认证功能
stream: True/False,默认为True,获取内容立即下载开关
verify : True/False,默认为True,认证SSL证书开关
cert: 本地SSL证书路径

requests.get(url, params=None,**args)

get函数就是对request的在封装,进行get请求

def get(url, params=None, **args):
    requests.request("GET", url, params, **args)
requests.post(url, data=None,**args)

post函数也是对request封装,进行post请求

requests.head(…)

获取头部信息

requests.put(…)

put请求

requests.patch(…)

提交局部修改,节省流量

requests.delete(…)

delete请求

Response对象介绍

上述请求方法返回值都是Response对象

r = requests.get("http://www.baidu.com")
type(r)
'''
<class 'requests.models.Response'>
'''
dir(r)
'''
['__attrs__', '__bool__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__nonzero__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_content', '_content_consumed', 'apparent_encoding', 'close', 'connection', 'content', 'cookies', 'elapsed', 'encoding', 'headers', 'history', 'iter_content', 'iter_lines', 'json', 'links', 'ok', 'raise_for_status', 'raw', 'reason', 'request', 'status_code', 'text', 'url']
'''

着重介绍如下Response属性:
url:访问的URL
status_code:状态码
reason:返回结果,状态码后边的值 HTTP/1.1 200 OK
encoding: charset字段的值,默认IOS-8859-1
apparent_encoding:从内容分析到的编码,可以辅助encoding:字段
cookies:cookies
headers:响应头
history:重定向跳转过的地址
text:响应体字符串表示
content:响应体二进制表示
request:request对象
iter_lines:成员函数,返回生成器对象,可以按行迭代内容。
raise_for_status:如果请求返回失败会抛出异常,如果发送了一个错误请求(一个 4XX 客户端错误,或者 5XX 服务器错误响应),我们可以通过 Response.raise_for_status() 来抛出异常

bad_r = requests.get('http://httpbin.org/status/404')
print(bad_r.status_code)
'''
404
'''
bad_r.raise_for_status()
'''
Traceback (most recent call last):
  File "requests/models.py", line 832, in raise_for_status
    raise http_error
requests.exceptions.HTTPError: 404 Client Error
'''

参考文档Requests官方文档 地址:
http://docs.python-requests.org/zh_CN/latest/user/quickstart.html

Python 生态系统中,除了广受欢迎的 `requests` 之外,还有多个功能强大且灵活的 HTTP 客户端,适用于不同的使用场景和需求。以下是一些常见的替代方案: ### 1. **httpx** `httpx` 是一个现代、功能丰富的 HTTP 客户端,支持同步和异步请求,并兼容 Python 的类型提示系统。它与 `requests` 的 API 风格相似,但提供了对 HTTP/2 和异步 I/O 的原生支持。 示例代码: ```python import httpx response = httpx.get('https://example.com') print(response.status_code) print(response.text) ``` ### 2. **aiohttp** 如果需要进行异步网络请求,`aiohttp` 是一个专为异步操作设计的高性能 HTTP 客户端和服务器,基于 `asyncio` 实现非阻塞 I/O 操作。 示例代码: ```python import aiohttp import asyncio async def fetch(): async with aiohttp.ClientSession() as session: async with session.get('https://example.com') as response: print(response.status) print(await response.text()) asyncio.run(fetch()) ``` ### 3. **urllib3** `urllib3` 是 Python 标准 `urllib.request` 的增强版,提供更高效的连接池机制、线程安全、支持文件上传等高级特性。它被广泛用于其他(如 `requests`)的底层实现。 示例代码: ```python import urllib3 http = urllib3.PoolManager() response = http.request('GET', 'https://example.com') print(response.status) print(response.data.decode('utf-8')) ``` ### 4. **treq** `treq` 是基于 `Twisted` 构建的异步 HTTP 客户端,其 API 设计灵感来自 `requests`,适合已经使用或计划使用 `Twisted` 进行事件驱动编程的项目。 示例代码: ```python from treq import get def process_response(response): print(response.code) return response.text().addCallback(print) get('https://example.com').addCallback(process_response) ``` ### 5. **pycurl** `pycurl` 是对 `libcurl` 的封装,提供了非常高效的网络通信能力,适合处理大量并发请求或需要精细控制网络协议的场景。不过其 API 相对较为复杂,学习曲线较陡。 示例代码: ```python import pycurl from io import BytesIO buffer = BytesIO() c = pycurl.Curl() c.setopt(c.URL, 'https://example.com') c.setopt(c.WRITEDATA, buffer) c.perform() c.close() body = buffer.getvalue() print(body.decode('utf-8')) ``` ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值