python2 和python3 urllib问题

python2
python2 中提供了urllib 和 urllib2 两个模块

import urllib
urllib.urlencode(values)#其中values为所需要编码的数据,并且只能为字典
python3
python3 中也有urllib和urllib3 两个库,其中urllib几乎是python2 中urllib和urllib两个模块的集合,我们经常也最使用urllib模块,而urllib3 则作为一个拓展模块使用。

urllib.parse.urlencode(query, doseq=False, safe='', encoding=None, errors=None, quote_via=quote_plus)

应用
现我们模拟登陆CSDN网站:

from urllib import request
from urllib import parse
from urllib.request import urlopen
 
values = {'username': '[email protected]', '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)

上边这个是python3中写法

下边这个是python2中 的写法

#coding:utf-8
import linecache
import urllib
import urllib2

message +=" 银行卡验证总量:"+ "2350"+": 同程银行卡验证数量:"+"2331"

test_data = {'message':message}

test_data_urlencode = urllib.parse.urlencode(test_data)

requrl = "http://172.30.1**.**:9876/sendMessage"

#req = urllib2.Request(url = requrl,data =test_data_urlencode)

#res_data = urllib2.urlopen(req)

req = urllib.request.Request(url = requrl,data =test_data_urlencode)

res_data = urllib.request.urlopen(req)

res = res_data.read()

print (res)

你可能感兴趣的:(python2 和python3 urllib问题)