requests库是Python中非常流行的HTTP库,它提供了多种方法来发送HTTP请求。以下是一些常用的requests方法:
get(url, params=None, **kwargs): 发送GET请求。params参数用于传递URL编码的查询字符串,**kwargs用于传递其他HTTP请求头或参数。response = requests.get('https://api.example.com/data', params={'key': 'value'})
post(url, data=None, json=None, **kwargs): 发送POST请求。data参数用于传递表单数据,json参数用于传递JSON格式的数据,**kwargs用于传递其他HTTP请求头或参数。response = requests.post('https://api.example.com/login', data={'username': 'user', 'password': 'pass'}, json={'key': 'value'})
put(url, data=None, **kwargs): 发送PUT请求。data参数用于传递表单数据,**kwargs用于传递其他HTTP请求头或参数。response = requests.put('https://api.example.com/resource/1', data={'key': 'value'})
delete(url, **kwargs): 发送DELETE请求。**kwargs用于传递其他HTTP请求头或参数。response = requests.delete('https://api.example.com/resource/1')
head(url, **kwargs): 发送HEAD请求。**kwargs用于传递其他HTTP请求头或参数。response = requests.head('https://api.example.com/resource/1')
options(url, **kwargs): 发送OPTIONS请求。**kwargs用于传递其他HTTP请求头或参数。response = requests.options('https://api.example.com/resource/1')
request(method, url, **kwargs): 发送自定义HTTP请求。method参数可以是上述任何HTTP方法,url参数是请求的URL,**kwargs用于传递其他HTTP请求头或参数。response = requests.request('PATCH', 'https://api.example.com/resource/1', data={'key': 'value'})
这些方法返回一个Response对象,包含了请求的响应信息,如状态码、响应头和响应内容。你可以使用Response对象的方法(如.text、.json()、.content等)来获取和处理响应数据。