Python字典键错误无法解决。

5

我正在对一个庞大的链接列表进行状态检查,我的代码片段如下:

link = 'http://xyz'
proxyDict = { "http" : "ip:80", "https" : "https://ip:443"}
r = requests.get(link, allow_redirects=False, verify=False)
http_status = r.status_code
print (r.headers)

# check the status and react accordingly

if http_status == 200 and r.headers['content-length'] == "0":
   print ('Link Alive - NO content'+';'+str(http_status)+';'+link, file = log)
elif http_status == 200 and "text/html" in r.headers['content-type']:
   print ('External- direct HTML link'+';'+str(http_status)+';'+link, file = log)  
elif http_status == 200 and "application" in r.headers['content-type']:
   print ('External- direct HTML link'+';'+str(http_status)+';'+link, file = log)

执行代码时,我会收到以下错误提示:
    return self._store[key.lower()][1]
    KeyError: 'content-length'

头部输出如下:
CaseInsensitiveDict({'status': '200', path=/; HttpOnly, shpuvid=rBBcnFJUTliSHV+hA5lLAg==; expires=Thu, 08-Oct-15 18:26:32 GMT;'connection': 'keep-alive', 'cache-control': 'max-age=0, private, must-revalidate', 'date': 'Tue, 08 Oct 2013 18:26:32 GMT', 'content-type': 'text/html; charset=utf-8', 'x-rack-cache': 'miss'})

我知道错误存在是因为
没有键"content-length",但是当不满足时,它必须跳转到下一个条件,但事实并非如此,而是停止代码执行,抛出上述错误。
有何建议?这可能是一个愚蠢的问题,但对于初学者来说是一个很好的学习机会。
3个回答

10

不要使用方括号表示法,而是使用字典中的r.headers.get('content-length')获取内容长度。这不会抛出键错误,而是返回None。

很好,您可以使用任一表示法从字典中检索值。许多时候,您希望抛出键错误,以便不会忽略问题。在这种情况下,似乎应使用dictionary.get()。


3

键错误通常意味着该键不存在。

我猜测self._store[key.lower()][1]无效(不存在)

来自官方 Python 文档:

异常 KeyError

当映射(字典)中没有找到键时触发。


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接