如何从eMail主体解析HTML - Python

时间:2013-07-14 16:52:12

标签: python html email beautifulsoup email-parsing

我正在尝试解析python中的传入电子邮件。 我收到的电子邮件是部分文本部分HTML。 我想获取HTML部分并在HTML中找到一个表。

我尝试过使用beatifulsoup。但是在尝试下一个代码时,bs只获得第一个“”部分而不是所有HTML部分:

# connecting to the gmail imap server
m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login(user,pwd)
# use m.list() to get all the mailboxes, "INBOX" to get only inbox
m.select("INBOX")
resp, items = m.search(None, '(UNSEEN)') # you could filter using the IMAP rules here (check http://www.example-code.com/csharp/imap-search-critera.asp)
items = items[0].split() # getting the mails id

for emailid in items:
    # getting the mail content
    resp, data = m.fetch(emailid, '(UID BODY[TEXT])')
    text = str(data[0][1])
    soup = bs(text)

如何在整个HTML部分使用'bs'? 或者,还有其他方法可以从电子邮件正文中解析出一个html表吗?

'bs'对我来说似乎是最好的,因为我想找到一个包含特定关键字的特定HTML Body,而'bs'搜索可以检索整个表并让我迭代它。

1 个答案:

答案 0 :(得分:3)

显然,我使用了错误的解析器。

一旦我改成'lxml'解析器,它就可以正常工作。

需要更改下一行:

soup = bs(text,"lxml");