1.查看本机python版本:python --version
2.查看是否安装pip:pip -V
3.安装pip:
sudo easy_install pip
4.安装requests:pip install requests
若报错,则使用pip install requests --user
5.发送get请求
import requests
myaddress_url='http://xxx.com/api/v1/myaddress'
myaddress=requests.get(myaddress_url)
print(myaddress.status_code)
print(myaddress.text)
6.
在很多时候,发送请求后,服务端会对发送请求方进行身份识别,如果请求中缺少识别信息或存在错误的识别信息,
会造成识别失败,返回401.
import requests
login_url='http://xxx.com/api/v1/user/login'
userinfo={"ua":"username","pw":"password"}
login=requests.post(login_url,json=userinfo)
cookies=login.cookies #获取登录后的cookies内容
myaddress_url='http://xxxx/api/v1/myaddress'
myaddress=requests.get(myaddress_url,cookies=cookies) #在请求中带入cookies
print(myaddress.status_code)
print(myaddress.text)
7.有时候需要的验证信息在header里,需要带header进行请求
import requests
url = 'http://pizza.jd.com/api/v1/groups/group1/credentials'
headers = {'Cookie': 'xxxxxx......'}
r = requests.get(url,headers=headers)
print(r.status_code)
print(r.text)
8.需要参数时
import requests
url = "https://httpbin.org/get"
params = {"show_raw":1}
headers = {'User-Agent': 'python-requests/2.18.4'}
r = requests.get(url,params=params,headers=headers)
print(r.status_code)
print(r.json())
print(r.json()["headers"])
9.运行脚本
终端进入python后输入命令python xx.py