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模块~~~

  • 相关阅读:
    centos下安装Anaconda
    centos下安装python2.7.9和pip以及数据科学常用的包
    mysql基础(5)-关联(mysql+pandas)
    mysql基础(4)-数据导入
    mysql基础(3)-高级查询
    mysql基础(2)-数据处理(mysql+pandas)
    mysql基础(1)-基本操作
    创建线程的三种方法
    Jar 包 及运行Jar包
    导出成可运行jar包时所遇问题的解决办法
  • 原文地址:https://www.cnblogs.com/yanglang/p/7144457.html
Copyright © 2011-2022 走看看