前言
在Python中,我们通常使用urllib中的urlencode方法将字典编码,用于提交数据给url等操作,但是在Python2和Python3中urllib模块中所提供的urlencode的包位置有些不同。
对于Python2
Python2中提供了urllib和urllib2两个模块。
urlencode方法所在位置为:
urllib.urlencode(values) # 其中values为所需要编码的数据,并且只能为字典
- 1
- 例如模拟登陆优快云网站,示例程序如下
import urllib2
values = {"username":"962457839@qq.com","password":"XXXX"}
data = urllib.urlencode(values)
url = "https://passport.youkuaiyun.com/account/login?from=http://my.youkuaiyun.com/my/mycsdn"
request = urllib2.Request(url,data)
response = urllib2.urlopen(request)
print response.read()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
对于Python3
Python3中也有urllib和urllib3两个库,其中urllib几乎是Python2中urllib和urllib2两个模块的集合,所以我们最常用的urllib模块,而urllib3则作为一个拓展模块使用。
urlencode方法所在位置
urllib.parse.urlencode(values)
- 1
- 例如模拟登陆优快云网站,示例程序如下:
from urllib import request
from urllib import parse
from urllib.request import urlopen
values = {'username': '962457839@qq.com', 'password': 'XXXX'}
data = parse.urlencode(values).encode('utf-8') # 提交类型不能为str,需要为byte类型
url = 'https://passport.youkuaiyun.com/account/login?from=http://my.youkuaiyun.com/my/mycsdn'
request = request.Request(url, data)
response = urlopen(request)
print(response.read().decode())
本文详细介绍了在Python2和Python3中如何使用不同的模块进行URL编码。Python2使用urllib.urlencode,而Python3则使用urllib.parse.urlencode。通过示例展示了如何用这些方法来模拟登录优快云网站。
10万+

被折叠的 条评论
为什么被折叠?



