1. 程式人生 > >python之使用request模塊發送post和get請求

python之使用request模塊發送post和get請求

jpg 二進制格式 request requests 下載到本地 aca user www pwd

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()

python之使用request模塊發送post和get請求