为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕的地8271018 2021-11-30 18:28:18
我正在尝试编写一些一旦运行就会返回电子邮件正文的内容。到目前为止我所拥有的是:from exchangelib import Credentials, Accountimport urllib3from bs4 import BeautifulSoupcredentials = 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 新手,可以使用一些帮助。我能做些什么来解决这个问题?
查看完整描述

2 回答

?
白衣非少年

TA贡献1155条经验 获得超0个赞

正如您的错误所表明的那样,您需要将您的return 内部函数


from exchangelib import Credentials, Account

import urllib3

from bs4 import BeautifulSoup


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

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


def get_email(span): # a function that can return values

    return span.text


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'):

        email_result = get_email(span) # call function and save returned value in a variable



查看完整回答
反对 回复 2021-11-30
?
函数式编程

TA贡献1807条经验 获得超9个赞

保留字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. 然后您可以使用该列表供以后使用。


查看完整回答
反对 回复 2021-11-30
  • 2 回答
  • 0 关注
  • 154 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信