Python:keyrerror/IOError withurllib.urlopen

2024-06-01 11:11:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将一些文本传递给这个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?谢谢。在


Tags: ofthetextapijsonurlrequestthis
2条回答

您引用的是完整的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

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

^{pr2}$

使用urllib.urlencode只对查询字符串进行编码,如下所示:

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

对整个URL进行编码将对斜杠和冒号进行编码,并且您希望它们保持未编码状态,以便将其正确解析为URL(不要误认为是本地文件)。在

相关问题 更多 >