我正在编写这段代码,我正在从网站上抓取网页,获取值并将其分配给dictionary变量。然后,我将发送一封电子邮件,其中包含HTML格式的键和值对
我陷入了在HTML部分显示字典键和值对的困境。我尝试发送电子邮件,但电子邮件已成功发送到目标,但是,HTML中的字典值正在打印,并且我得到了原样中提到的代码
import requests
from bs4 import BeautifulSoup as BS
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
me = "examplefrom@gmail.com"
you = "exampleto@gmail.com"
def webScrape():
dict={}
URL="Website URL"
page=requests.get(URL)
soup=BS(page.content, 'html.parser')
results=soup.find_all('div', class_="blog-posts clear")
for results_element in results:
title_elem = results_element.find_all('h2', class_='home-title')
link_element=results_element.find_all('a', class_="story-link", href=True)
for index,(title,link) in enumerate(zip(title_elem, link_element)):
dict[str(title.text)]=str(link['href'])
return dict
dictionary_values=webScrape()
msg = MIMEMultipart()
password = "password"
msg['Subject'] = "Your Webscrape Data"
msg['From'] = me
msg['To'] = you
html = """\
<html>
<head></head>
<body>
{% for key, value in dictionary_values.iteritems() %}
<br/>
<h3><a href={{key}}>{{value}}</a></h3>
<br/>
{% endfor %}
</body>
</html>
"""
part2 = MIMEText(html, 'html')
msg.attach(part2)
server = smtplib.SMTP('smtp.gmail.com: 587')
server.starttls()
server.login(msg['From'], password)
server.sendmail(msg['From'], msg['To'], msg.as_string())
server.quit()
print("Send Successfully")
您似乎在使用Jinja2模板语法,但实际上还没有在此处导入或使用Jinja2,您可以这样做:
相关问题 更多 >
编程相关推荐