我正在尝试向我发送一封电子邮件,其中包含我进行的一些网络抓取的结果。抓取全部在一个函数中进行。因此,我尝试将功能设置为电子邮件的消息,但是它不起作用。
这是我的代码(仍然很新,所以请不要对代码进行过多的抨击,我知道我仍然可以对其进行大量重构)
from bs4 import BeautifulSoup
from email.mime.text import MIMEText
import requests
import smtplib
page = requests.get("https://www.sportsinteraction.com/soccer/england/premier-league-betting/")
soup = BeautifulSoup(page.content, 'html.parser')
matches = soup.find_all(class_="game")
def betting_odds(data):
for games in data:
teams = games.find_all(class_="name")
odds = games.find_all(class_="price wide")
if len(games.find_all(class_="date")) > 0:
print(games.find(class_="date").get_text())
team1 = teams[0].get_text()
draw = teams[1].get_text()
team2 = teams[2].get_text()
odds1 = odds[0].get_text()
odds_draw = odds[1].get_text()
odds2 = odds[2].get_text()
print("{} {} \n{} {} \n{} {} \n".format(team1, odds1, draw, odds_draw, team2, odds2))
fromx = 'email@email.com'
to = 'email@emai.com'
msg = MIMEText('Here are the odds for the upcoming premier league games\n\n{}'.format(betting_odds(matches)))
msg['Subject'] = 'Premier League Odds'
msg['From'] = fromx
msg['To'] = to
smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.login('Email@email.com', 'password')
smtpObj.sendmail(fromx, to, msg.as_string())
smtpObj.quit()
运行此命令时,结果将完全按照我希望它们出现的方式完全显示在Shell中,然后发送电子邮件。收到电子邮件后,它包含主题,并且消息的第一行是正确的,但随后显示“无”。
非常感谢您的帮助!
答案 0 :(得分:0)
此问题已解决。我通过创建一个变量来保存字符串来完成它,并继续通过循环将它们连接在一起。然后我在最后返回了变量。
干杯!