
Python中的requests库是一个非常流行的HTTP库,它被广泛用于发送HTTP请求。这个库简单易用,功能强大,非常适合用于网络编程和Web开发。下面我将介绍几个常见的使用场景和代码示例:
这是最常见的使用场景之一。通过GET请求,我们可以从服务器检索数据。
import requestsresponse = requests.get('https://api.example.com/data')print(response.text)
这将输出从指定URL获取的数据。
POST请求通常用于向服务器发送数据,如提交表单。
import requestsdata = {'key': 'value'}response = requests.post('https://api.example.com/submit', data=data)print(response.text)
这将输出服务器对POST请求的响应。
requests库也可以用来上传文件。
import requestsfiles = {'file': open('example.txt', 'rb')}response = requests.post('https://api.example.com/upload', files=files)print(response.text)
显示文件上传后的服务器响应。
requests可以轻松处理Cookies。
import requestsresponse = requests.get('https://www.example.com')print(response.cookies)
打印从网站接收的Cookies。
有时我们需要发送自定义的请求头。
import requestsheaders = {'User-Agent': 'My User Agent 1.0'}response = requests.get('https://api.example.com', headers=headers)print(response.text)
输出使用自定义请求头发送GET请求的结果。
处理请求过程中可能出现的错误。
import requestsfrom requests.exceptions import HTTPErrortry:response = requests.get('https://api.example.com')response.raise_for_status()except HTTPError as http_err:print(f'HTTP error occurred: {http_err}')except Exception as err:print(f'Other error occurred: {err}')else:print('Success!')
显示请求是否成功,或者捕获并显示错误信息。
这些只是requests库功能的一部分,它还支持会话管理、SSL证书验证、代理支持等高级功能。通过这些示例,你可以开始探索requests库的强大功能。