处理TypeError:' NoneType'在BeautifulSoup

时间:2015-03-07 17:40:04

标签: python exception beautifulsoup typeerror

我正在使用BeautifulSoup抓取网页,而我查找csrf令牌的行有时会抛出TypeError。

代码是:

csrf = soup.find(id="csrfToken-postModuleForm")['value']

返回的错误是:

TypeError: 'NoneType' object has no attribute '__getitem__'

我希望继续使用脚本,如果该值不存在而不是抛出异常 - 任何想法如何可能?

1 个答案:

答案 0 :(得分:3)

像这样的东西

try:
    # Try to get the CSRF token
    csrf = soup.find(id="csrfToken-postModuleForm")['value']
except(TypeError, KeyError) as e:
    # Token not found. Replace 'pass' with additional logic.
    pass

在这里,您可以添加任何其他逻辑,例如:

    print("CSRF Not Found.")

确保您了解CSRF令牌的工作原理。它们是网络安全的重要组成部分。