返回语句不返回电子邮件的值

我正在尝试编写一些一旦运行就会返回电子邮件正文的内容。到目前为止我所拥有的是:


from exchangelib import Credentials, Account

import urllib3

from bs4 import BeautifulSoup


credentials = Credentials('fake@email', 'password')

account = Account('fake@email', credentials=credentials, autodiscover=True)


for item in account.inbox.all().order_by('-datetime_received')[:1]:

    html = item.unique_body

    soup = BeautifulSoup(html, "html.parser")

    for span in soup.find_all('font'):

        return span.text

我的问题是最后一行阅读return span.text。如果我用 替换这一行print(span.text),它会完美运行并打印电子邮件的正文。但是,当替换为 时return,它会引发错误读数SyntaxError: 'return' outside function。我一直在研究这个问题,我似乎无法弄清楚它为什么会抛出这个问题。我是 Python 新手,可以使用一些帮助。我能做些什么来解决这个问题?


慕的地8271018
浏览 155回答 2
2回答

白衣非少年

正如您的错误所表明的那样,您需要将您的return 内部函数from exchangelib import Credentials, Accountimport urllib3from bs4 import BeautifulSoupcredentials = Credentials('fake@email', 'password')account = Account('fake@email', credentials=credentials, autodiscover=True)def get_email(span): # a function that can return values    return span.textfor item in account.inbox.all().order_by('-datetime_received')[:1]:    html = item.unique_body    soup = BeautifulSoup(html, "html.parser")    for span in soup.find_all('font'):        email_result = get_email(span) # call function and save returned value in a variable

函数式编程

保留字return只能在如下函数中使用:def hello(name):    return "hello " + name如果你不打算在一个函数内工作(你现在不是)尝试做这样的事情:emails = []for item in account.inbox.all().order_by('-datetime_received')[:1]:    html = item.unique_body    soup = BeautifulSoup(html, "html.parser")    for span in soup.find_all('font'):        emails.append(span.text)发生的事情是您现在将span.text对象添加到名为emails. 然后您可以使用该列表供以后使用。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python