Skip to main content
 首页 » 编程设计

python之使用 urllib 读取 mashabe API

2025年04月02日9zlslch

我有这段代码可以在 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. 

请您参考如下方法:

在这一行中:

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)