python字典键错误无法解决

标签 python http python-2.7 dictionary python-requests

我正在对大量链接执行状态检查,我的代码片段如下:

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

我知道错误存在是因为 header output 没有键“content-length”,但是当 if condition 不满足时它必须跳转到下一个 elif 条件不会发生,而是停止代码执行并抛出上述错误。

有什么建议吗?可能是一个愚蠢的问题,但对于初学者来说是一件好事。

最佳答案

不使用括号表示法,而是使用字典中的 r.headers.get('content-length'),它不会抛出键错误,只会返回 None。

很高兴您可以使用任何一种表示法从字典中检索值。很多时候您希望抛出该关键错误,以免让问题被忽视。在这种情况下,dictionary.get() 似乎就是您想要的。

关于python字典键错误无法解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19255628/

相关文章:

python - 检查字典键是否在字典列表(元组)中

php - Apache 2 多 View 和图像/* 请求的 406 错误

java - 集群环境中 JMS 主题的 HTTP 使用者

python - 使用多处理模块的脚本不会终止

python - 在生产中禁用 pyc 文件

python - 傅立叶变换的逆给出 “data type not supported”错误

python - 导入错误 : No module named 'tasks'

java - 通过在 java 中编码获取 URL 响应

bash - Google Colab 脚本抛出 "Transport endpoint is not connected"

python - 将重复项添加到列表