1. Python requests模块的安装
Python requests模块可以通过pip进行安装,在命令行中输入:
pip install requests
安装完成后,可以在Python程序中引入requests模块:
import requests
2. Python requests模块的使用
requests模块提供了一系列方法,可以用来发送HTTP请求,常用的有:
- get:发送GET请求
- post:发送POST请求
- put:发送PUT请求
- delete:发送DELETE请求
下面给出一个发送GET请求的示例:
import requests url = 'https://www.example.com/' response = requests.get(url) print(response.text)
上面代码中,引入requests模块,调用requests.get()方法,传入URL,发送GET请求,调用response.text属性,获取返回的文本数据。
3. Python requests模块的其他用法
除了上面介绍的基本用法,requests模块还有一些其他的用法:
- 可以设置请求头:
headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36' } response = requests.get(url, headers=headers)
- 可以设置请求参数:
params = { 'key1': 'value1', 'key2': 'value2' } response = requests.get(url, params=params)
- 可以设置超时:
response = requests.get(url, timeout=10)
- 可以设置代理:
proxies = { 'http': 'http://127.0.0.1:1080', 'https': 'http://127.0.0.1:1080' } response = requests.get(url, proxies=proxies)
以上就是,通过requests模块可以方便地发送HTTP请求,可以设置请求头、请求参数、超时、代理等参数,以实现更加灵活的网络请求。