Python2和Python3中urllib库中urlencode的使用注意事项
前言
在Python中,我们通常使用urllib中的urlencode方法将字典编码,用于提交数据给url等操作,但是在Python2和Python3中urllib模块中所提供的urlencode的包位置有些不同。
对于Python2
Python2中提供了urllib和urllib2两个模块。
urlencode方法所在位置为:
urllib.urlencode(values)#其中values为所需要编码的数据,并且只能为字典
例如模拟登陆CSDN网站,示例程序如下
importurllib2 values={"username":"962457839@qq.com","password":"XXXX"} data=urllib.urlencode(values) url="https://passport.csdn.net/account/login?from=http://my.csdn.net/my/mycsdn" request=urllib2.Request(url,data) response=urllib2.urlopen(request) printresponse.read()
对于Python3
Python3中也有urllib和urllib3两个库,其中urllib几乎是Python2中urllib和urllib2两个模块的集合,所以我们最常用的urllib模块,而urllib3则作为一个拓展模块使用。
urlencode方法所在位置
urllib.parse.urlencode(values)
例如模拟登陆CSDN网站,示例程序如下:
fromurllibimportrequest fromurllibimportparse fromurllib.requestimporturlopen values={'username':'962457839@qq.com','password':'XXXX'} data=parse.urlencode(values).encode('utf-8')#提交类型不能为str,需要为byte类型 url='https://passport.csdn.net/account/login?from=http://my.csdn.net/my/mycsdn' request=request.Request(url,data) response=urlopen(request) print(response.read().decode())
ps:修复在python3中importwinrandom错误问题
问题:在windows的python3使用PyCrypto出现ImportError:Nomodulenamed'winrandom'错误
处理:修改python3安装目录下的 lib/Crypto/Random/OSRNG/nt.py文件中找到
importwinrandom
修改为
fromCrypto.Random.OSRNGimportwinrandom
总结
以上所述是小编给大家介绍的Python2和Python3中urllib库中urlencode的使用注意事项,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!