昨天花了大半天研究python的urllib库。今天发现广泛使用的是第三方库——requests。用了requests之后开始怀疑昨天一天在干嘛了~强烈推荐
1. get请求
1.1 普通get请求
import requests
# 普通get请求
req = requests.get("http://httpbin.org/get")
print(req.status_code, req.reason)
print(req.text)
1.2 带参数的get请求
# 带参数的get请求
param = {'username': '123', 'password': '456'}
req = requests.get("http://httpbin.org/get", param)
print(req.text)
print(req.json())
2. Post请求
# post请求
req = requests.post("http://httpbin.org/post", {'username': '123', 'password': '456'})
print(req.json())```
3. 自定义headers
# 自定义headers
ua = 'NiuBai Browser'
headers = {'User-Agent': ua}
req = requests.get("http://httpbin.org/get", headers=headers)
print(req.json())
4. 带cookies的请求
# 带cookies的请求
# cookies = {'userid': '123','token': 'xxxxxxxxxxxxxxxxxxxxxxxxxx'}
cookies = dict(userid='123', token='xxxxxxxxxxxxxxxxxxxxxxxxxx')
req = requests.get("http://httpbin.org/cookies", cookies=cookies)
print(req.json())
5. 带Basic-Auth的请求
# 带Basic-auth的请求
auth = ('admin', '123456')
req = requests.get("http://httpbin.org/basic-auth/admin/123456", auth=auth)
print(req.json())
6. Session的使用
# Session的使用
# 获得一个Session
s = requests.Session()
# 设置两条cookies
s.get("http://httpbin.org/cookies/set/userid/123456")
s.get("http://httpbin.org/cookies/set/password/xxxxxxxxxxxxxx")
# 查看该站保存的cookies
req = s.get("http://httpbin.org/cookies")
print(req.json())
7.代理的使用
推荐代理网站:免费代理
# 在requests中使用代理
print("不使用代理时的ip:", requests.get("http://httpbin.org/ip").json())
print("使用代理时的ip:", requests.get("http://httpbin.org/ip",
proxies={'http': '103.78.213.226:45075'}).json())
撒花~
网友评论