zoukankan      html  css  js  c++  java
  • 【Python】Python网络编程

    python内置封装了很多常见的网络协议的库,因此python成为了一个强大的网络编程工具,这里是对python的网络方面编程的一个简单描述。

    urllib 和 urllib2模块

    urllib 和urllib2是python标准库中最强的网络工作库。这里简单介绍下urllib模块。本次主要用urllib模块中的常用的几个模块:

     
    urlopen
    parse
    urlencode
    quote
    unquote
    _safe_quoters
    unquote_plus
     

    GET请求:

    使用urllib 进行http协议的get请求,并获取接口的返回值:

     
    from urllib.request import urlopen
    url = 'http://127.0.0.1:5000/login?username=admin&password=123456' #打开url #urllib.request.urlopen(url) #打开url并读取数据,返回结果是bytes类型:b'{ "code": 200, "msg": "xe6x88x90xe5x8ax9fxefxbcx81" } ' res = urlopen(url).read() print(type(res), res) #将bytes类型转换为字符串 print(res.decode())
     

    POST请求:

     
    from urllib.request import urlopen
    from urllib.parse import urlencode
    url = 'http://127.0.0.1:5000/register' #请求参数,写成json类型,后面是自动转换为key-value形式 data = { "username": "55555", "pwd": "123456", "confirmpwd": "123456" } #使用urlencode(),将请求参数(字典)里的key-value进行拼接 #拼接成username=hahaha&pwd=123456&confirmpwd=123456 #使用encode()将字符串转换为bytes param = urlencode(data).encode() #输出结果:b'pwd=123456&username=hahaha&confirmpwd=123456' print(param) #post请求,需要传入请求参数 res = urlopen(url, param).read() res_str = res.decode() print(type(res_str), res_str)
     

    注:使用urllib请求post接口时,以上例子,post接口的请求参数类型是key-value形式,不适用json形式入参。

    Quote模块

    对请求的url中带有特殊字符时,进行转义处理。

     
    from urllib.parse import urlencode, quote, _safe_quoters, unquote, unquote_plus
    url3 = 'https://www.baidu.com/?tn=57095150_2_oem_dg:..,\ ' #url中包含特殊字符时,将特殊字符进行转义, 输出:https%3A//www.baidu.com/%3Ftn%3D57095150_2_oem_dg%3A..%2C%5C%20 new_url = quote(url3) print(new_url)
     

    Unquote模块

    对转义过的特殊字符进行解析操作。

     
    from urllib.parse import urlencode, quote, _safe_quoters, unquote, unquote_plus
    url4 = 'https%3A//www.baidu.com/%3Ftn%3D57095150_2_oem_dg%3A..%2C%5C%20' #将转义后的特殊字符进行解析,解析为特殊字符 new_url = unquote(url4) #输出结果:https://www.baidu.com/?tn=57095150_2_oem_dg:.., print(new_url) #最大程度的解析 print('plus:', unquote_plus(url4))
     

    以上就是简单介绍下urllib,对接口处理时还请参考requests模块~~~

  • 相关阅读:
    FZU 2112 并查集、欧拉通路
    HDU 5686 斐波那契数列、Java求大数
    Codeforces 675C Money Transfers 思维题
    HDU 5687 字典树插入查找删除
    HDU 1532 最大流模板题
    HDU 5384 字典树、AC自动机
    山科第三届校赛总结
    HDU 2222 AC自动机模板题
    HDU 3911 线段树区间合并、异或取反操作
    CodeForces 615B Longtail Hedgehog
  • 原文地址:https://www.cnblogs.com/yanglang/p/7144457.html
Copyright © 2011-2022 走看看