Python 2.7 更改“;data=urllib.parse.urlencode(值)";到Python2.7
每个人,我都必须将一些代码从Python3.*更改为2.7,但是,我不知道Python2.7中的代码Python 2.7 更改“;data=urllib.parse.urlencode(值)";到Python2.7,python-2.7,python-3.x,urllib2,urllib,Python 2.7,Python 3.x,Urllib2,Urllib,每个人,我都必须将一些代码从Python3.*更改为2.7,但是,我不知道Python2.7中的代码data=urllib.parse.urlencode(values) 蟒蛇3* python 2.7 这里是python 2.7中的urllib函数调用的等效函数,应该可以工作 import urllib import urllib2 from contextlib import closing def sendsms(phonenumber,textcontent): url = '
data=urllib.parse.urlencode(values)
蟒蛇3*
python 2.7
这里是python 2.7中的
urllib
函数调用的等效函数,应该可以工作
import urllib
import urllib2
from contextlib import closing
def sendsms(phonenumber,textcontent):
url = 'http://urls?'
values = {'username' : 'hello',
'password' : 'world',
'dstaddr' : phonenumber ,
'smbody': textcontent
}
data = urllib.urlencode(values)
data = data.encode('Big5')
req = urllib2.Request(url, data)
with closing(urllib2.urlopen(req)) as response:
the_page = response.read()
编辑:感谢@Cc L指出使用
时出现的错误。。。由于未实现上下文管理器,与urlopen
相同。下面是另一种方法,上下文管理器在块完成时返回关闭关闭页面 首先,感谢wolfsgang在上面的回答,然后我修改了代码,它可以工作了
import urllib
import urllib2
def sendsms(phonenumber,textcontent):
url = 'http://urls?'
values = {'username' : 'hello',
'password' : 'world',
'dstaddr' : phonenumber ,
'smbody': textcontent
}
data = urllib.urlencode(values)
data = data.encode('Big5')
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
感谢您的回答,您的代码基本上是正确的,我认为“使用urllib2.urlopen(req)作为响应:the_page=response.read()”必须更改为“response=urllib2.urlopen(req)”,否则将出现错误“AttributeError:AddInfo URL实例没有属性“exit”
import urllib
import urllib2
from contextlib import closing
def sendsms(phonenumber,textcontent):
url = 'http://urls?'
values = {'username' : 'hello',
'password' : 'world',
'dstaddr' : phonenumber ,
'smbody': textcontent
}
data = urllib.urlencode(values)
data = data.encode('Big5')
req = urllib2.Request(url, data)
with closing(urllib2.urlopen(req)) as response:
the_page = response.read()
import urllib
import urllib2
def sendsms(phonenumber,textcontent):
url = 'http://urls?'
values = {'username' : 'hello',
'password' : 'world',
'dstaddr' : phonenumber ,
'smbody': textcontent
}
data = urllib.urlencode(values)
data = data.encode('Big5')
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)