网络编程
from urllib import request
from urllib import request url='http://127.0.0.1:8999/login?username=zr&pwd=123456' req=request.urlopen(url) #打开一个URL,发get请求 content=req.read().decode()#获取返回结果,如果不.decode就是B开头,二进制类型的 f=open('baidu.html','w',encoding='utf-8')#在day8目录下生成一个baidu.html的文件 f.write(content) #网络爬虫,从其它网站上,获取一些有用的内容
import request
import requests import random,json,pymysql #发get请求 # url='http://api.nnzhp.cn/api/user/stu_info' # # data={'stu_name':'小黑'} #请求数据 # # req=requests.get(url,params=data) #发get请求 # # print(req.json())#字典 # # print(req.text) #string,json串 #返回的都是什么 #返回的类型是什么 #2、发post请求 # url='http://api.nnzhp.cn/api/user/login' # data={'username':'niuhanyang','passwd':'aA123456'} # req=requests.post(url,data) # print(req.json()) #3、入参是json类型的 # phone=random.randint(13000000000,13500000000) # # url='http://api.nnzhp.cn/api/user/add_stu' # # data={ # "name": "小黑", # "grade": "天蝎座", # "phone": phone, # "sex": "男", # "age": 28, # "addr": "河南省济源市北海大道32号" # } # # req=requests.post(url,json=data) # print(req.json()) #添加cookies的 # url='http://api.nnzhp.cn/api/user/gold_add' # data={'stu_id':'1','gold':'50'} # req=requests.post(url,data,cookies={'niuhanyang':'8cddec0ae482ae542d595684c0f78f12'}) # print(req.json()) #添加header # url='http://api.nnzhp.cn/api/user/all_stu' # header={'Referer':'http://api.nnzhp.cn/'} # req=requests.get(url,headers=header) # print(req.json()) #上传文件 url='http://api.nnzhp.cn/api/file/file_upload' data={ 'file':open('333',encoding='utf-8') } req=requests.post(url,files=data) print(req.json()) #data={'file':open('c:\user\bjniuhanyang\Desktop\图.jpg','rb')}#图片不能传utf-8,需要传rb格式,二进制读模式
下载文件
#下载文件 import requests url='http://www.nnzhp.cn/wp-content/uploads/2018/01/soup.jpg' req=requests.get(url) print(req.content) fw=open('s.jpg','wb') fw.write(req.content) #返回的二进制文件