使用urllib阅读mashabe API

我有这段代码来阅读python 2中的Mashape.com API。我如何在python 3中阅读它?使用urllib阅读mashabe API

代码

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. 

回答:

在这一行:

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)

以上是 使用urllib阅读mashabe API 的全部内容, 来源链接: utcz.com/qa/264470.html

回到顶部