Python:KeyError/IOError 与 urllib.urlopen

标签 python json urllib urlopen

我正在尝试将一些文本传递给此 readability API像这样:

text = 'this reminds me of the Dutch 2001a caravan full of smoky people Auld Lang Syne'
# construct Readability Metrics API url
request_url = 'http://ipeirotis.appspot.com/readability/GetReadabilityScores?format=json&text=%s' % text
request_url = urllib.quote_plus(request_url.encode('utf-8'))
# make request
j = json.load(urllib.urlopen(request_url))

虽然我在最后一行得到了这个错误:

[Errno 2] No such file or directory: 'http://ipeirotis.appspot.com/readability/GetReadabilityScores?format=json&text=this+reminds+me+of+the+Dutch+2001a+caravan+full+of+smoky+people+Auld+Lang+Syne'

但是,错误中的 URL 是有效的,并且在您访问它时会返回响应。如何对 URL 进行编码以便我可以使用 urlopen?非常感谢。

最佳答案

您引用的是完整的 url,包括 http://等等。如果你尝试打印 request_url 的实际值,你会得到

>>> print request_url
http%3A%2F%2Fipeirotis.appspot.com%2Freadability%2FGetReadabilityScores%3Fformat
%3Djson%26text%3Dthis+reminds+me+of+the+Dutch+2001a+caravan+full+of+smoky+people
+Auld+Lang+Syne

这不是你想要的。您只想引用您想要作为网站的单个参数的部分。我尝试了以下方法,它似乎有效:

text = 'this reminds me of the Dutch 2001a caravan full of smoky people Auld Lang Syne'
# construct Readability Metrics API url
request_url = 'http://ipeirotis.appspot.com/readability/GetReadabilityScores?format=json&text=%s' % urllib.quote_plus(text.encode('utf-8'))
# make request
j = json.load(urllib.urlopen(request_url))

关于Python:KeyError/IOError 与 urllib.urlopen,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8377330/

相关文章:

json - select和desc json配置单元表失败

c# - 将小数序列化为 JSON,如何四舍五入?

javascript - 按字母顺序对对象列表进行排序

python - 为什么字典不像 urllib post 中的字符串?

python - 生成器无法与 Python 中的字节连接

python - 使用PyMC3的指数函数时出错

python - 列表实际上如何使用for循环在python中工作?

python - 更快地下载 ~500 个网页(循环)

python - urllib.parse.quote 不会采用 utf8

Python 请求开启多个实例