zoukankan      html  css  js  c++  java
  • 模拟 GET 和 POST 请求

    解析 JSON 数据的模块——JSON 模块,它用于 Python 原始类型与 JSON 类型的相互转换。


    (1).如果解析文件,可以用 dump()和 load()方法函数.转自:https://www.cnblogs.com/xiaomingzaixian/p/7286793.html

    (2).如果解析字符串,则 用下述两个函数:

    1 dumps():编码 [Python -> Json]  
    2 dict => object list, tuple => array  str => string True => true 
    3 int, float, int- & float-derived Enums => number False => false None => null 
    4  
    5 loads():解码 [Json -> Python]  
    6 object => dict array => list string => str number (int) => int  
    7 number(real) => float true =>True false => False null => None 

    模拟 GET 请求的代码

     1 # -*- coding: utf-8 -*-
     2 """
     3 Created on Tue Apr  7 15:01:15 2020
     4 
     5 @author: ZKYAAA
     6 """
     7 
     8 import urllib.request
     9 import json
    10 
    11 #检验证书问题
    12 import ssl   
    13 #方法一:全局取消证书验证 
    14 #ssl._create_default_https_context=ssl._create_unverified_context 
    15 
    16 get_url="http://gank.io/api/data/"+urllib.request.quote("福利")+"/1/1"   
    17 get_resp=urllib.request.urlopen(get_url)
    18 
    19 #方法二:使用ssl创建未经验证的上下文,在urlopen()中传入上下文参数
    20 context=ssl._create_unverified_context()
    21 get_resp=urllib.request.urlopen(get_url,context=context)
    22 
    23 
    24 get_result=json.loads(get_resp.read().decode('utf-8'))
    25 #后面的参数用于格式化JSON输出格式
    26 get_result_format=json.dumps(get_result,indent=2,
    27                              sort_keys=True,ensure_ascii=False)
    28 
    29 print("get_result_format")

    模拟 POST 请求的代码

     1 # -*- coding: utf-8 -*-
     2 """
     3 Created on Tue Apr  7 15:37:38 2020
     4 
     5 @author: ZKYAAA
     6 """
     7 
     8 
     9 import urllib.request
    10 import urllib.parse
    11 import json
    12  
    13 post_url="http://www.baidu.login"
    14 phone="13555555555"
    15 password="111111"
    16 values={
    17     'phone':phone,
    18     'password':password
    19 }
    20 
    21 data=urllib.parse.urlencode(values).encode(encoding='utf-8')
    22 req=urllib.request.Request(post_url,data)
    23 resp=urllib.request.urlopen(req)
    24 result=json.load(resp.read())
    25 print(json.dumps(result,sort_keys=True,indent=2,ensure_ascii=False))
  • 相关阅读:
    Python之路第十二天,高级(5)-Python操作Mysql,SqlAlchemy
    Python之路第十二天,高级(4)-Python操作rabbitMQ
    Python之路第十一天,高级(3)-线程池
    day11 消息队列、多线程、多进程、协程
    day10 多进程、多线程(一)
    day09编程之socket
    day08面向对象(二)
    day07面向对象(初级篇)
    day06反射和正则
    day05开发 (字符串格式化和常用模块)
  • 原文地址:https://www.cnblogs.com/ZKYAAA/p/12654182.html
Copyright © 2011-2022 走看看