【问题标题】:IndexError: List Index out of Range when grabbing gmail textIndexError:抓取 gmail 文本时列出超出范围的索引
【发布时间】:2014-11-26 12:32:39
【问题描述】:

我正在使用此代码登录我的 gmail 帐户并从 steampowered 的电子邮件中检索文本。

else:
      g = gmail.login(emailAddress, emailPassword)
      # Check for emails until we get Steam Guard code
      for i in range(0, 3):
        mails = g.inbox().mail(sender="noreply@steampowered.com", unread=True)
        if mails:
          mail = mails[-1]
          mail.fetch()
          #print re.findall(r"you'll need to complete the process: ([A-Z0-9]{5})", mail.body)
          guardCode = re.findall(r"you'll need to complete the process: ([A-Z0-9]{5})", mail.body)[0]
          mail.read()
          mail.delete()
          g.logout()
          return guardCode
        else:
          time.sleep(3)

我得到一个

IndexError: 列表索引超出范围

在这一行:

guardCode = re.findall(r"you'll need to complete the process: ([A-Z0-9]{5})", mail.body)[0]

这是因为

re.findall(r"you'll need to complete the process: ([A-Z0-9]{5})", mail.body)

返回

[]

所以列表是空的。为什么是空的?

这是电子邮件的格式:

您是否正在使用新的浏览器或 Steam 应用程序登录 Steam?这是 完成该过程所需的 Steam 令牌代码:XXXXXX

编辑: Gmail 是来自 here 的自定义 python 模块。 编辑#2:这是电子邮件的更好表示:

亲爱的XXX,

您是否正在使用新的浏览器或 Steam 应用程序登录 Steam?这里是 完成该过程所需的 Steam 令牌代码:

XXXXX

如果您最近没有尝试从设备登录 Steam 位于 XXXX(美国),其他人可能正在尝试访问 你的帐户。您可以在线查看有关此登录尝试的更多信息。

如果您怀疑其他人可能试图访问您的帐户, 请:

【问题讨论】:

    标签: python regex python-2.7 gmail steam


    【解决方案1】:

    问题是因为you’ll 中的。这不是普通的单引号'

    >>> s = "Are you logging into Steam using a new browser or Steam app? Here’s the Steam Guard code you’ll need to complete the process: XXXXX"
    >>> re.findall(r"you’ll need to complete the process: ([A-Z0-9]{5})", s)
    ['XXXXX']
    

    【讨论】:

    • 哇。你是怎么猜到的?
    • 如何将它与mail.body结合起来?
    • 将上述代码中的s 替换为mail.body(即存储您要使用的输入的变量。)
    • 不,我的意思是我从电子邮件中获取值 XXXXX,所以我不能将 mail.body 设置为字符串,它必须是电子邮件的正文。
    • 对不起,我不明白你的意思。我只回答了So the list is empty. Why is it empty? 问题。等等,一定会有人解决你的问题的。
    【解决方案2】:

    我解决了我的问题。我刚刚删除了所有换行符并将电子邮件正文作为一个完整的字符串。感谢所有帮助过的人!

    str = re.sub('\s+',' ', mail.body)
    guardCode = re.findall(r'to complete the process: ([A-Z0-9]{5})', str)[0]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-08
      • 2023-03-28
      • 1970-01-01
      • 2015-01-18
      相关资源
      最近更新 更多