1 版本变化
Python2 之前使用 urllib2 库,在版本升级后出现问题,因为在3版本中库进行了整合,具体变动如下:
Py3.x:
删除了Urllin2库,统一更改为Urllib
Urllib库
变化:
在Pytho2.x中使用import urllib2——-对应的,在Python3.x中会使用import urllib.request,urllib.error。
在Pytho2.x中使用import urllib——-对应的,在Python3.x中会使用import urllib.request,urllib.error,urllib.parse。
在Pytho2.x中使用import urlparse——-对应的,在Python3.x中会使用import urllib.parse。
在Pytho2.x中使用import urlopen——-对应的,在Python3.x中会使用import urllib.request.urlopen。
在Pytho2.x中使用import urlencode——-对应的,在Python3.x中会使用import urllib.parse.urlencode。
在Pytho2.x中使用import urllib.quote——-对应的,在Python3.x中会使用import urllib.request.quote。
在Pytho2.x中使用cookielib.CookieJar——-对应的,在Python3.x中会使用http.CookieJar。
在Pytho2.x中使用urllib2.Request——-对应的,在Python3.x中会使用urllib.request.Request.
2 问题解决
在进行一个post请求时,postman 里面可以正常请求到数据,但是一模一样放到python里面就不行了,后面通过抓包发现了问题。
部分代码如下:
formdata = {
"analyzer": "ik_smart",
"text": text
}
data = parse.urlencode(formdata).encode(encoding='UTF8')
req = request.Request(url, headers=self.headers, data=data)
res = request.urlopen(req)
res = res.read()
以上方式会将json数据形成analyzer=ik_smart的形式,无法让接口正常解析。
修改为如下代码:
data = json.dumps(formdata) data = bytes(data, "utf8") req = request.Request(url, headers=self.headers, data=data) res = request.urlopen(req) res = res.read()
可以正常进行访问。
注:data = bytes(data, "utf8") 需要转成bytes,否则会报错。
本文详细介绍了从Python2升级到Python3时,urllib库的变化及对应替换方法,包括导入语句和常用函数的更新。并提供了解决post请求数据格式问题的示例,帮助开发者顺利完成库迁移。
3243

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



