python3的urllib3和requests及问题解决

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,否则会报错。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值