GoodZhang在学Python(十三)--Python3数据get与post提交

urllib.request 模块定义了一些类及方法,用于帮助我们访问URL

urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False)

方法是用来打开url的方法,其中url可以是一个合法的url字符串,或者是一个request对象;data必须是字节数据类型的。详细介绍可参见python3官方文档urllib.request。

关于数据提交的两种方式get、post的区别,在此就不再赘述,下面给出两种提交方式的例子:

Get:

# ----------------------------------
__author__ = 'zWX231671'
__description__ = ''
# ----------------------------------
import urllib.parse
import urllib.request

data = urllib.parse.urlencode({'name': 'abc', 'password': '123'})
response = urllib.request.urlopen('http://127.0.0.1:8080/test/index.jsp?%s' % data)

html = response.read()
print(html.decode('utf-8'))

Post:

# ----------------------------------
__author__ = 'zWX231671'
__description__ = ''
# ----------------------------------
import urllib.parse
import urllib.request

url = 'http://127.0.0.1:8080/test/index.jsp'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values = {
    'name': 'abc',
    'password': '123'
}
data = urllib.parse.urlencode(values)
# that params output from urlencode is encoded to bytes before it is sent to urlopen as data
data = data.encode('utf-8')
req = urllib.request.Request(url, data)
response = urllib.request.urlopen(req)

html = response.read()
print(html.decode('utf-8'))


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值