python学习笔记:网络请求——requests模块


上面讲过的urllib模块太麻烦了,还有一个比较方便的模块,就是requests模块,好用到你怀疑人生·^_^,一定要会哦

需要安装,pip install requests即可,下面是requests模块的实例。

import requests

response = requests.get('http://www.baidu.com')
print(response.status_code)  # 打印状态码
print(response.url)          # 打印请求url
print(response.headers)      # 打印头信息
print(response.cookies)      # 打印cookie信息
print(response.text)  #以文本形式打印网页源码
print(response.content) #以字节流形式打印
import requests

# ====发get请求====
url='http://www.nnzhp.cn/archives/423'
res=requests.get(url)
print(res.text)

# ====添加cookie\header==== url='http://www.nnzhp.cn/archives/423' res=requests.get(url,params={"xx":"xx"},cookies={'token':"token12345"},headers={'Content-Type':"application/json"}) print(res.text)
# ====发post请求==== url='http://api.nnzhp.cn/api/user/login' res=requests.post(url,data={"username":"niuhanyang","passws":"aA123456"}) print(res.json())#返回的就是一个字典 # print(res.text)#这样的话返回的是json字符串
#====下载文件file==== mp3_url='http://xxxxxxx.mp3' res=requests.get(mp3_url) mp3=res.content # 返回二进制内容 f=open('a.mp3','wb') f.write(mp3) f.close()#将a.mp3文件保存到当前路径下 #====文件上传==== url='http://api.nnzhp.cn/api/file/file_upload' res=requests.post(url,filtes={'file':open('a.mp3','rb')}) # 参数名file,参数是open('a.mp3','rb'),rb的意思是用二进制方式打开 print(res.json()) #====入参是json类型==== url='http://api.nnzhp.cn/api/user/add_stu' data={"phone":"15000000001","grade":"金牛座","name":"小红"}# 入参是一个字典 res=requests.post(url,json=data)# 因为入参是json,所以直接写json=data print(res.json())

猜你喜欢

转载自www.cnblogs.com/haifeima/p/9928365.html
今日推荐