前两个小demo urllib模块在python3中的写法
urllib模块在python3中的写法 自己测试了一下可以的:
# -*- coding:utf-8 -*-
# python2 环境下才要写上面那句话
# python3 中把python2 的urllib和 urllib2 集成urllib包,
import urllib.request
from urllib.parse import urlencode
URL_IP = "http://localhost:8000/ip"
URL_GET = "http://127.0.0.1:8000/get"
def use_demo_urllib():
"""python3"""
response = urllib.request.urlopen(URL_IP)
# 返回文件状态
print(">>>Response status:",response.getcode())
# 返回文件头部信息
Response_Headers = response.info()
print(">>>Response Headers:\n", Response_Headers)
# print(">>>Response Headers:\n",Response_Headers.items())
# 返回响应体
Response_body = ''.join([line.decode() for line in response.readlines()])
print(">>>Response Body:\n",Response_body)
def use_params_parse():
# 构建请求参数
params = {"param1":"hello","param2":"world"}
request_params = urlencode(params)
print(request_params)
# 发送请求
response = urllib.request.urlopen('?'.join([URL_GET, "%s"]) % request_params)
# 返回文件头部信息
Response_Headers = response.info()
print(">>>Response Headers:\n", Response_Headers)
# print(">>>Response Headers:\n",Response_Headers.items())
print(">>>Status Code:",response.getcode())
# 返回响应体
Response_body = ''.join([line.decode() for line in response.readlines()])
print(">>>Response Body:\n",Response_body)
if __name__ == "__main__":
print(">>>Use simple urllib:")
use_demo_urllib()
print()
print(">>>Use params urllib.parse:")
use_params_parse()
print("in this file , __name__ is %s" % __name__)