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