Search code examples
pythonpython-3.xseleniumselenium-chromedriversmtplib

Print Element to Email Body Issue Python Selenium SMTPLIB


Im really stuck here. Ive learnt how to use Selenium to scrape a price and in the above example it is for a fuel / gas / petrol website. I can get the price to print in my Terminal:

print("Best Petrol Price in Perth today is:", elem.text)

Though I am stuck in how to reference that price into the body of an email - Im using smtplib and Gmail. Credentials redacted and emails replaced with dummyholders.

from webdriver_manager.chrome import ChromeDriverManager
browser = webdriver.Chrome(ChromeDriverManager().install())
browser.execute_script("window.open('https://www.fuelwatch.wa.gov.au/fuelwatch/pages/home.jspx');")
browser.switch_to.window(browser.window_handles[-1])
elem = browser.find_element_by_css_selector('#homepage\:j_idt84\:bestMetroPrices\:0\:j_idt96\:1\:bestMetroPrice')
print("Best Petrol Price in Perth today is:", elem.text)
price = elem.text
import smtplib
conn = smtplib.SMTP('smtp.gmail.com', 587)
type (conn)
conn
conn.ehlo()
conn.starttls()
conn.login('XXXXXXXXXXXXX', 'XXXXXXXXXXXXX')
conn.sendmail('example@mail.com', 'example2@mail.com', 'Subject: Best Petrol Price in Perth today is:\n\n "price"')
conn.quit()

The code runs and works, however the body of the email states "empty message" or "price". How can I reference the element text correctly and reference it in the body of the email? Thanks in advance for your help.


Solution

  • I you want to include the price into the email, may want to try using f string :

    msg=f'Subject: Best Petrol Price in Perth today is:\n\n {price}'
    

    Can find out from here- https://www.geeksforgeeks.org/formatted-string-literals-f-strings-python/