python - 搜索电子邮件并打开取消订阅链接

标签 python python-3.x

我目前正在开发 Automate the Boring Stuff 的一个项目,我应该编写一个程序来扫描我的电子邮件并找到取消订阅链接并在浏览器中打开它们。

这是我现在拥有的代码,但我不确定为什么它不会在新浏览器中打开任何电子邮件。任何帮助将不胜感激。

#! Python3
# Write a program that scans through your email account,finds all the
# unsubscribe links in all your emails, and automatically opens them in a browser.

import imapclient
import pyzmail
import webbrowser
import bs4

# User input
user_email = input('Enter your email: ')
user_pass = input('Enter your password: ')

# Connects to IMAP Server
imap_obj = imapclient.IMAPClient('imap.gmail.com', ssl=True)
imap_obj.login(user_email, user_pass)
imap_obj.select_folder('INBOX', readonly=True)
UIDs = imap_obj.gmail_search('after:2018/07/13 before:2018/07/14 unsubscribe')
raw_messages = imap_obj.fetch(UIDs, ['BODY[]'])

for i in UIDs:
    message = pyzmail.PyzMessage.factory(raw_messages[i][b'BODY[]'])
    raw_soup = message.html_part.get_payload().decode(message.html_part.charset)
    soup = bs4.BeautifulSoup(raw_soup, 'html.parser')
    for unsub in soup.findAll('a'):
        print(unsub)
        break
        if 'Unsubscribe' in unsub:
            webbrowser.open(unsub)

imap_obj.logout()

最佳答案

您需要检查元素文本中是否包含“取消订阅”。 in 对于不可迭代的事物(例如 bs4 元素标签)将无法按您的预期工作。类似的东西

    soup = bs4.BeautifulSoup(raw_soup, 'html.parser')
    for unsub in soup.find_all('a'):
        print((unsub.text, unsub.get('href')))
        if 'unsubscribe' in unsub.text.lower():
            webbrowser.open(unsub.get('href'))

(注意最后一行中的unsub.href,您需要访问这些标签的属性,而不是对标签本身的引用)

关于python - 搜索电子邮件并打开取消订阅链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51370043/

相关文章:

python - django UnreadablePostError : request data read error 错误

python - psycopg2 更新查询破坏了我的 PostgreSQL 表

python - 如何从 qtreeWidgetItem 中获取comboBox.currentText() 和 SpinBox.text()

python - FileNotFoundError:[WinError 2]尝试使用pysndfx时,系统找不到指定的文件

Python gmplot 'centerLat' 未定义

python - 实现 group_by_owners 字典

python - 无法从网站相应地获取两个字段

python - 同等权重的网格管理器中按钮大小不同?

python - 我可以在 python 中使用 selenium webdriver 滚动网页吗

python - django 1.8 View 中的循环