2011-12-04 20 views
1

我想一些文字传递给该readability API像这样:的Python:KeyError异常/ IO错误使用了urllib.urlopen

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)) 

我得到这个错误在最后一行,但:

[错误2]没有这样的文件或目录:'http://ipeirotis.appspot.com/readability/GetReadabilityScores?format=json & text = this +提醒我+ +荷兰语+ 2001a + caravan + full + of + smoky +人+ Auld + Lang + Syne'

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

回答

3

您正在引用完整的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)) 
+0

打我吧:) –

+0

非常感谢,这使得更有意义! – soulprovidr

1

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

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

编码整个URL将编码的斜线和冒号,和你希望这些文件保持未编码状态,这样它将被正确解析为URL(而不是误认为本地文件)。

+0

感谢您的回答,我喜欢这个网站! – soulprovidr