使用urllib读取mashabe API

2024-04-25 09:58:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个密码要读Mashape.com网站python2中的API。我如何在python3中阅读它?在

编码

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)

我尝试了这个代码,但它有以下错误:

^{pr2}$

错误:

TypeError: POST data should be bytes or an iterable of bytes. It cannot be of type str.

Tags: textimportcomjsonurldatarequestparams