python之使用request模块发送post和get请求

8 篇文章 0 订阅
# -*- coding:utf-8 -*-
"""
python 使用request模块发送post和get请求
参考:https://www.cnblogs.com/mpp0905/p/8383522.html 和书籍128页
"""

import requests

import requests
import json

#发送get请求并得到结果
url = 'http://api.nnzhp.cn/api/user/stu_info?stu_name=小黑马 '#请求接口
req = requests.get(url)#发送请求
print(req.text)#获取请求,得到的是json格式
print(req.json())#获取请求,得到的是字典格式
print(type(req.text))
print(type(req.json()))

#发送post请求,注册接口
url = 'http://api.nnzhp.cn/api/user/user_reg'
data = {'username':'mpp0130','pwd':'Mp123456','cpwd':'Mp123456'}
req = requests.post(url,data)#发送post请求,第一个参数是URL,第二个参数是请求数据
print(req.json())

#入参是json
url = 'http://api.nnzhp.cn/api/user/add_stu'
data = {'name':'mapeipei','grade':'Mp123456','phone':15601301234}
req = requests.post(url,json=data)
print(req.json())

#添加header
url = 'http://api.nnzhp.cn/api/user/all_stu'
header = {'Referer':'http://api.nnzhp.cn/'}
res = requests.get(url,headers=header)
print(res.json())

# 添加cookie
url = 'http://api.nnzhp.cn/api/user/gold_add'
data = {'stu_id':231,'gold':123}
cookie = {'niuhanyang':'7e4c46e5790ca7d5165eb32d0a895ab1'}
req = requests.post(url,data,cookies=cookie)
print(req.json())

#上传文件
url = 'http://api.nnzhp.cn/api/file/file_upload'
f = open(r'E:\besttest\te\python-mpp\day7\练习\11.jpg','rb')
r = requests.post(url,files={'file':f})
users_dic = r.json()
print(users_dic)

# 下载文件
url = 'http://www.besttest.cn/data/upload/201710/f_36b1c59ecf3b8ff5b0acaf2ea42bafe0.jpg'
r = requests.get(url)
print(r.status_code)#获取请求的状态码
print(r.content)#获取返回结果的二进制格式
fw = open('mpp.jpg','wb')
fw.write(r.content)
fw.close()

#把浏览器页面下载到本地   保存网页,可以理解为简单的爬虫工具
url='http://www.nnzhp.cn/archives/630'
r = requests.get(url)
f = open('nnzhp.html','wb')
f.write(r.content)
f.close()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值