Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Return语句未返回电子邮件的值_Python_Error Handling_Beautifulsoup_Return - Fatal编程技术网

Python Return语句未返回电子邮件的值

Python Return语句未返回电子邮件的值,python,error-handling,beautifulsoup,return,Python,Error Handling,Beautifulsoup,Return,我正在尝试写一些东西,一旦运行就会返回电子邮件正文文本。到目前为止,我得到的是: from exchangelib import Credentials, Account import urllib3 from bs4 import BeautifulSoup credentials = Credentials('fake@email', 'password') account = Account('fake@email', credentials=credentials, autodisco

我正在尝试写一些东西,一旦运行就会返回电子邮件正文文本。到目前为止,我得到的是:

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

我的问题是最后一行读取
返回span.text
。如果我将这一行替换为
print(span.text)
,它运行得很好,可以打印电子邮件的正文。但是,当替换为
return
时,它会抛出一个错误,读取
SyntaxError:“return”在函数外部
。我一直在深入研究这个问题,但我似乎不明白为什么它会抛出这个问题。我是Python新手,需要一些帮助。我能做些什么来解决这个问题呢?

正如您的错误所示,您需要将您的
返回值
放在函数中

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

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