Чтение mashabe API с использованием urllib

У меня есть этот код для чтения Mashape.com API в Python 2. Как я могу прочитать его в 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.

1 ответ

Решение

В этой строке:

request = urllib.request.Request(URL, urllib.parse.urlencode(params), headers)

Попробуйте заменить на

data = urllib.parse.urlencode(params).encode('utf-8')
request = urllib.request.Request(URL, data, headers)
Другие вопросы по тегам