python的网络请求,主要是进行Http协议类接口调用,进行接口测试等。
一、urllib库,python内嵌的库,不太好用。
from urllib import request,parse import json # url = 'http://baidu.com' # req = request.urlopen(url) #打开一个url # content = req.read().decode() # fw = open('nnzhp.html', 'w', encoding='utf-8') # fw.write(content) # #网络爬虫,从其他的网站上,获取一些有用的内容 #get请求 # url = 'http://www.baidu.com/' # req = request.urlopen(url) # content = req.read().decode() #获取返回结果 # res_dic = json.loads(content) #返回的结果转为字典 # if res_dic.get('error_code') == 0: # print('测试通过.') # else: # print('测试失败',res_dic) #post请求 url = 'http://xxxxxx/api/user/login' data = { 'usernmae':'admin', 'passwd': 'aA123456' }#请求数据 data = parse.urlencode(data) # print(parse.urlencode(data))#urlencode,自动给你拼好参数 req = request.urlopen(url, data.encode()) #发送Post请求 print(req.read().decode())
二、requests模块,好用的模块
import requests import random #1、发get请求 # url = 'http://xxxxxx/api/user/stu_info' # data = {'stu_name':'xxxx'} #请求数据 # req = requests.get(url, params=data) # print(req.json()) # print(req.text) # print(type(req.json())) #dict # print(type(req.text)) #str #返回的都是什么 #返回的类型是什么 #中文的好使吗 #2、发post请求 url = 'http://xxxxxxx/api/user/login' data = {'username':'xxxxx','passwd': 'xxxxx'}#请求数据 req = requests.post(url, data) print(req.json()) #3、入参是json类型的 # url = 'http://xxxxxx/api/user/add_stu' # phone = random.randint(10000000000,99999999999) # data = { # "name":"xxxx", # "grade":"天蝎座", # "phone":phone, # "sex":"女", # "age":28, # "addr":"河南省济源市北海大道32号" # } # req = requests.post(url, json=data) # print(req.json()) #4、入参是json类型的 # url = 'http://xxxxxxx/api/user/gold_add' # data = {'stu_id':468,'gold':120000} # req = requests.post(url, data, cookies={'niuhanyang':'337ca4cc825302b3a8791ac7f9dc4bc6'}) # print(req.json()) #5、添加header # url = 'http://xxxxxxx/api/user/all_stu' # header = {'Referer': 'http://api/xxxxxxx/'} # req = requests.get(url, headers=header) # print(req.json()) #{'error_code': 4, 'msg': '请求来路不正确'} #6、上传文件 # url = 'http://xxxxxxxx/api/file/file_upload' # # data = {'file':open('笔记-day08.txt',encoding='utf-8')} #上传文件 # data = {'file':open('12222.jpg', 'rb')} #上传图片 # req = requests.post(url, files=data) # print(req.json()) #7、下载图片 #http://xxxxx/wp-content/uploads/2018/01/soup.jpg # url = 'http://wwwxxxxx/wp-content/uploads/2018/01/soup.jpg' # req = requests.get(url) # print(req.content)#返回的二进制的东西 # # fw = open('s.jpg', 'wb') # fw.write(req.content) # url = 'http://wwwxxxxxx/' # req = requests.get(url) # print(req.content)#返回的二进制的东西 # # fw = open('pymysql.html', 'wb') # fw.write(req.content) #http://up.mcyt.net/?down/46779.mp3 url = 'http://up.mcyt.net/?down/46779.mp3' req = requests.get(url) print(req.content)#返回的二进制的东西 fw = open('aaaa,.mp3', 'wb') fw.write(req.content)