I am working on this code, I am doing web scraping from a website and getting the values and assigning it to the dictionary variable. Then, I am sending an email which contains the key and value pairs in the HTML format.
I got stuck in the displaying dictionary key and value pairs in the HTML part. I tried sending email but email is sent successfully to the target but, the dictionary values in HTML are getting printed and I am getting the code which is mentioned in the as it is.
JavaScript
x
66
66
1
2
import requests
3
from bs4 import BeautifulSoup as BS
4
import smtplib
5
from email.mime.multipart import MIMEMultipart
6
from email.mime.text import MIMEText
7
me = "examplefrom@gmail.com"
8
you = "exampleto@gmail.com"
9
10
11
def webScrape():
12
dict={}
13
URL="Website URL"
14
page=requests.get(URL)
15
16
soup=BS(page.content, 'html.parser')
17
results=soup.find_all('div', class_="blog-posts clear")
18
for results_element in results:
19
title_elem = results_element.find_all('h2', class_='home-title')
20
link_element=results_element.find_all('a', class_="story-link", href=True)
21
for index,(title,link) in enumerate(zip(title_elem, link_element)):
22
dict[str(title.text)]=str(link['href'])
23
return dict
24
25
26
dictionary_values=webScrape()
27
28
29
30
msg = MIMEMultipart()
31
password = "password"
32
msg['Subject'] = "Your Webscrape Data"
33
msg['From'] = me
34
msg['To'] = you
35
html = """
36
<html>
37
<head></head>
38
<body>
39
40
{% for key, value in dictionary_values.iteritems() %}
41
<br/>
42
<h3><a href={{key}}>{{value}}</a></h3>
43
<br/>
44
{% endfor %}
45
46
</body>
47
</html>
48
"""
49
50
51
part2 = MIMEText(html, 'html')
52
msg.attach(part2)
53
server = smtplib.SMTP('smtp.gmail.com: 587')
54
server.starttls()
55
server.login(msg['From'], password)
56
57
server.sendmail(msg['From'], msg['To'], msg.as_string())
58
59
server.quit()
60
61
print("Send Successfully")
62
63
64
65
66
Advertisement
Answer
You seem to be using Jinja2 template syntax, but you haven’t actually imported or used Jinja2 here, which you can do like this:
JavaScript
1
21
21
1
from jinja2 import Environment
2
3
jinja_env = Environment(autoescape=True)
4
5
template = jinja_env.from_string("""
6
<html>
7
<head></head>
8
<body>
9
10
{% for key, value in dictionary_values.items() %}
11
<br/>
12
<h3><a href={{key}}>{{value}}</a></h3>
13
<br/>
14
{% endfor %}
15
16
</body>
17
</html>
18
""")
19
20
html = template.render(dictionary_values=dictionary_values)
21