学习笔记(29):21天通关Python(仅视频课)-案例实操:使用urllib模块读取网络资源及提交请求(上)...

立即学习:https://edu.csdn.net/course/play/24797/282209?utm_source=blogtoedu

'''
urllib.request子模块下包含一个非常使用的urllib.request.urlopen(url,data=None)方法,该方法用于打开url指定的资源,并从中读取数据
使用urlOpen()函数时可以通过data参数向被请求的URL发送数据
发送Get请求参数时,只咬将请求参数最佳到URL后面即可
如需发送put、patch、delete等请求,此时需要使用urllib.request.Request来构建请求参数
构建Request对象时,可以通过method参数制定请求方法

'''
import urllib.request as request
import urllib.parse as up

# 访问地址
url = 'http://localhost:8088/python/testPython.php'
# 请求参数

params = {'name': 'python', 'age': 29, 'sex': '男'}
params_post = {'name': 'python', 'age': 29, 'sex': '1'}

# Get请求
# with request.urlopen('http://localhost:8088/python/testPython.php?%s' % up.urlencode(params)) as f:
#     print(up.unquote(f.read().decode('utf-8')))

# Post请求
data = up.urlencode(params_post)
with request.urlopen(url, data=data.encode('UTF-8')) as f:
    print(f.read().decode('utf-8'))

# PUT请求
data = up.urlencode(params_post).encode('UTF-8')
#如需发送put、patch、delete等请求,此时需要使用urllib.request.Request来构建请求参数
req=request.Request(url,data=data,method='PUT')
with request.urlopen(req) as f:
    print(f.read().decode('utf-8'))


# 查看网页源代码
# with request.urlopen('http://localhost:8088/python/testPython.php') as f:
#     print(f.read().decode('utf-8'))
发布了39 篇原创文章 · 获赞 29 · 访问量 898

猜你喜欢

转载自blog.csdn.net/happyk213/article/details/105252419
今日推荐