python--网络请求

一、urllib模块

from urllib.request import urlopen
from urllib.parse import urlencode
import json

#get请求,不需要传参
url ='http://www.nnzhp.cn/archives/423'
res =urlopen(url).read().decode()  #获取到的内容为二进制类型的,decode()成字符串
f=open('a.html','w',encoding='utf-8')
f.write(res)
f.close()

#post请求,需传参,且参数必须是二进制
url='http://api.nnzhp.cn/api/user/login'
data ={'username':'niuhanyang','passwd':'aA123456'}
res =urlopen(url,urlencode(data).encode()).read().decode()  #入参需要是二进制形式,所以要encode()
d=json.loads(res)
print(d)

二、requests模块

import requests

url ='http://www.nnzhp.cn/archives/423'
# 没有参数的get请求
res=requests.get(url)

#有参数的get请求,参数为k-v形式
res=requests.get(url,
                 params={'key':'value'},
                 cookies={'key':'value'},
                 headers={'key':'value'})
print(res.text)  #返回的是字符串


url='http://api.nnzhp.cn/api/user/login'
res=requests.post(url,
                  data={'username':'niuhanyang','passwd':'aA123456'})
print(res.json()) #返回字典
# print(res.text)#返回字符串

#返回歌曲、图片.....(二进制文件)
MP3_url='http://qiniuuwmp3.changba.com/1113525663.mp3'
res = requests.get(MP3_url)
mp3=res.content  #返回二进制
f=open('g.mp3','wb')
f.write(mp3)
f.close()


# 入参为file
url='http://api.nnzhp.cn/api/file/file_upload'
res=requests.post(url,files={'file':open('aa.txt','rb')})
print(res.json())

#入参为json
url='http://api.nnzhp.cn/api/user/add_stu'
data={'phone':'12345678654','age':2,'grade':'金牛座','name':'hehe'}
res=requests.post(url,json=data)
print(res.json())
原文地址:https://www.cnblogs.com/HathawayLee/p/9904467.html