Python:使用urllib.urlopen时出现KeyError/IOError

1 投票
2 回答
977 浏览
提问于 2025-04-17 07:40

我正在尝试将一些文本传递给这个 可读性 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] 没有这样的文件或目录: 'http://ipeirotis.appspot.com/readability/GetReadabilityScores?format=json&text=this+reminds+me+of+the+Dutch+2001a+caravan+full+of+smoky+people+Auld+Lang+Syne'

但是,错误中提到的这个网址是有效的,访问时会返回响应。那么,我该如何编码这个网址,以便可以使用 urlopen 呢?非常感谢。

2 个回答

1

使用 urllib.urlencode 只对查询字符串进行编码,像这样:

request_url = 'http://ipeirotis.appspot.com/readability/GetReadabilityScores?%s' % urllib.urlencode({'format': 'json', 'text': text})

如果把整个网址都编码的话,会把斜杠和冒号也编码,这样的话它们就会变得不正常,导致网址无法正确解析(可能会被误认为是本地文件)。

3

你引用了完整的网址,包括了 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))

撰写回答