亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

返回語句不返回電子郵件的值

返回語句不返回電子郵件的值

慕的地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 關注
  • 179 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號