Skip to content
Advertisement

How to display the Python Dictionary key and value pairs in HTML part of the python code

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.



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")





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:

from jinja2 import Environment

jinja_env = Environment(autoescape=True)

template = jinja_env.from_string("""
<html>
  <head></head>
  <body>
    
       {%% for key, value in dictionary_values.items() %%}
       <br/>
       <h3><a href={{key}}>{{value}}</a></h3>
       <br/>
       {%% endfor %%}

  </body>
</html>
""")

html = template.render(dictionary_values=dictionary_values)

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement