2016-11-14 57 views
0

我正在编写一个脚本来通过我的电子邮件来计算我在Uber游乐设施上花费了多少钱。 (优步向您发送收据给您的电子邮件,其中包括费用,我正在通过电子邮件查找费用,然后将其添加到阵列中)我使用1封电子邮件进行测试,但遇到问题同时试图循环所有的电子邮件。使用imaplib获取错误

我知道id_list(电子邮件ID列表)是一个完整的数组。当我把它打印出来,我得到:['4726', '5543', '5587', '5589', '5661', '5758', '5759', '5853', '5986', '6071', '6072', '6076', '6105', '6141', '6229']

这里是我完整的错误回溯:

Traceback (most recent call last): 
    File "/Users/Harrison/Desktop/Uber/Uber.py", line 22, in <module> 
    result,data = mail.fetch(id, "(RFC822") 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/imaplib.py", line 456, in fetch 
    typ, dat = self._simple_command(name, message_set, message_parts) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/imaplib.py", line 1088, in _simple_command 
    return self._command_complete(name, self._command(name, *args)) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/imaplib.py", line 918, in _command_complete 
    raise self.error('%s command error: %s %s' % (name, typ, data)) 
imaplib.error: FETCH command error: BAD ['Could not parse command'] 

这里是我的代码:

import imaplib 
import email 
from bs4 import BeautifulSoup 

final_cost1 = "" 
final_cost2 = "" 

cost_array = [] 

mail = imaplib.IMAP4_SSL('imap.gmail.com') 
mail.login('my email', 'my passowrd') 

mail.list() 
mail.select('inbox') 
result,data = mail.search(None, 'FROM', '"Uber Receipts"') 

ids = data[0] 
id_list = ids.split() 


for id in id_list: 
    result,data = mail.fetch(id, "(RFC822") 

    message_body = data[0][1] 

    uber_email = email.message_from_string(message_body) 
    for part in uber_email.walk(): 
     if part.get_content_type() == "text/html": 
      body = part.get_payload(None, decode=True) 

    soup = BeautifulSoup(body, 'html.parser') 
    #print soup.prettify() 

    for row in soup.find_all('td', attrs={"class" : "price final-charge"}): 
     final_cost1 = row.text.lstrip().strip() 

    for row in soup.find_all('td', attrs={"class" : "totalPrice chargedFare black"}): 
     final_cost2 = row.text.lstrip().strip() 

    if final_cost1 != "": 
     print final_cost1 
     cost_array.append(final_cost1) 
    if final_cost2 != "": 
     print final_cost2 
     cost_array.append(final_cost2) 

print cost_array 

回答

0

我的一部分愚蠢的错误。

这条线result,data = mail.fetch(id, "(RFC822")有一个错字。它应该是result,data = mail.fetch(id, "(RFC822)")