1.安装
pip install requests
2.使用
import requests //引入包
基本的get请求
response = requests.get('http://httpbin.org/get')
print(response.text)
带参数的get请求
第一种方式,直接将参数放在url中
response = requests.get(http://httpbin.org/get?name=gemey&age=22)
print(response.text)
第二种方式先将参数写在dict中,发起请求时用params来传递参数
data = {
'name': 'tom',
'age': 20
}
response = requests.get('http://httpbin.org/get', params=data)
print(response.text)
解析结果转为json
response = requests.get('http://httpbin.org/get')
print(response.text)
print(response.json()) #response.json()方法同json.loads(response.text)
print(type(response.json()))
加入请求头信息headers
url = 'https://api.github.com/some/endpoint'
headers = {'user-agent': 'my-app/0.0.1'}
r = requests.get(url, headers=headers)
使用post传参数
data = {'name':'tom','age':'22'}
response = requests.post('http://httpbin.org/post', data=data)
加入Cookie
url = 'http://httpbin.org/cookies'
cookies = dict(cookies_are='working')
r = requests.get(url, cookies=cookies)
获得请求到的Cookie
response = requests.get('http://www.baidu.com')
print(response.cookies)
print(type(response.cookies))
for k,v in response.cookies.items():
print(k+':'+v)
设置超时
requests.get('http://github.com', timeout=0.001)
请求结果
response = requests.get('http://www.baidu.com')
print(response.status_code) # 打印状态码
print(response.url) # 打印请求url
print(response.headers) # 打印头信息
print(response.cookies) # 打印cookie信息
print(response.text) #以文本形式打印网页源码
print(response.content) #以字节流形式打印
各种请求方式
import requests
requests.get('http://httpbin.org/get')
requests.post('http://httpbin.org/post')
requests.put('http://httpbin.org/put')
requests.delete('http://httpbin.org/delete')
requests.head('http://httpbin.org/get')
requests.options('http://httpbin.org/get')
身份验证
许多要求身份认证的web服务都接受 HTTP Basic Auth。这是最简单的一种身份认证,并且 Requests 对这种认证方式的支持是直接开箱即可用。
以 HTTP Basic Auth 发送请求非常简单:
from requests.auth import HTTPBasicAuth
requests.get('https://api.github.com/user',auth=HTTPBasicAuth('user', 'pass'))
<Response [200]>
事实上,HTTP Basic Auth 如此常见,Requests 就提供了一种简写的使用方式:
requests.get('https://api.github.com/user', auth=('user', 'pass'))
<Response [200]>
像这样在一个元组中提供认证信息与前一个 HTTPBasicAuth 例子是完全相同的。
网友评论