【发布时间】:2016-09-13 15:22:52
【问题描述】:
我有这段代码可以在 python 2 中读取 Mashape.com API。我如何在 python 3 中读取它?
代码
import urllib, urllib2, json
from pprint import pprint
URL = "https://getsentiment.p.mashape.com/"
text = "The food was great, but the service was slow."
params = {'text': text, 'domain': 'retail', 'terms': 1, 'categories': 1,'sentiment': 1, 'annotate': 1}
headers = {'X-Mashape-Key': YOUR_MASHAPE_KEY}
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request(URL, urllib.urlencode(params), headers=headers)
response = opener.open(request)
opener.close()
data = json.loads(response.read())
pprint(data)
我试过这段代码,但它有以下错误:
import urllib.parse
import urllib.request
URL = "https://getsentiment.p.mashape.com/"
text = "The food was great, but the service was slow."
params = {'text': text, 'domain': 'retail', 'terms': 1, 'categories': 1, 'sentiment': 1, 'annotate': 1}
headers = {'X-Mashape-Key': YOUR_MASHAPE_KEY}
opener = urllib.request.build_opener(urllib.request.HTTPHandler)
request = urllib.request.Request(URL, urllib.parse.urlencode(params), headers)
response = opener.open(request)
opener.close()
data = json.loads(response.read())
print(data)
错误:
TypeError: POST data should be bytes or an iterable of bytes. It cannot be of type str.
【问题讨论】:
-
发布您在使用 python 3 时遇到的问题,以及为什么您无法“阅读”
-
我不知道如何阅读它,我从某个地方复制了这段代码,但我没有为 python 3 找到这样的东西
-
是的,但是当你用 python 3 运行这段代码时会发生什么?
-
看起来 urllib2 在 python 3 中被改变了
-
哪一行出现此错误?
标签: python python-3.x mashape