【问题标题】:Python: KeyError/IOError with urllib.urlopenPython:带有 urllib.urlopen 的 KeyError/IOError
【发布时间】:2011-12-04 17:54:10
【问题描述】:

我正在尝试向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] 没有这样的文件或目录:'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?非常感谢。

【问题讨论】:

    标签: python json urllib urlopen


    【解决方案1】:

    您引用了完整的网址,包括 http:// 和其他内容。如果你尝试打印 request_url 的实际值,你会得到 ​​p>

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

    【讨论】:

    • 非常感谢,这更有意义!
    【解决方案2】:

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

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

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

    【讨论】:

    • 感谢您的回答,我喜欢这个网站!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-27
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多