Python requests 模块
Python的requests模块是一个非常强大的工具,它可以用来发送HTTP请求。以下是一些使用Python requests模块的常见方法:
- 发送GET请求:
import requests
response = requests.get('https://api.github.com/some/endpoint')
print(response.json())
- 发送POST请求:
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://api.github.com/some/endpoint', data=payload)
print(response.json())
- 发送带有header的请求:
import requests
headers = {'User-Agent': 'my-app/0.0.1', 'Accept': 'application/json'}
response = requests.get('https://api.github.com/some/endpoint', headers=headers)
print(response.json())
- 发送带有参数的请求:
import requests
params = {'param1': 'value1', 'param2': 'value2'}
response = requests.get('https://api.github.com/some/endpoint', params=params)
print(response.json())
- 使用timeout参数:
import requests
response = requests.get('https://api.github.com/some/endpoint', timeout=0.001)
print(response.json())
- 使用proxies参数:
import requests
proxies = {
'http': 'http://10.10.1.10:3128',
'https': 'http://10.10.1.10:1080',
}
response = requests.get('https://api.github.com/some/endpoint', proxies=proxies)
print(response.json())
- 使用cookies:
import requests
cookies = dict(cookies_are='working')
response = requests.get('https://api.github.com/some/endpoint', cookies=cookies)
print(response.json())
- 使用session对象来保持会话:
import requests
s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})
r = s.get('https://api.github.com/some/endpoint')
print(r.json())
以上就是一些使用Python requests模块的常见方法,你可以根据你的需求选择合适的方法来使用。
评论已关闭