easy_c0mpany80 easy_c0mpany80 - 4 months ago 21
Python Question

Write and send Gmail with Selenium for Python

I have just started using selenium with Python for the first time, after following a quick tutorial I am now trying to make a program with it that will login to Gmail and then send an email to a chosen email address.

I've gotten the login part done but had some problems with the composing a new email part (only works some of the time) and I get stuck everytime when it comes to writing the message body.

My code is below, I have tried reading the docs but Im having trouble getting the following to work in Gmail and the when I inspect the elements in gmail it seems a lot more complex than the basic html structures in the examples here:

http://selenium-python.readthedocs.org/locating-elements.html#locating-elements-by-tag-name

"""
Write a program that takes an email address and string of text on the command line and then, using Selenium,
logs into your email account and sends an email of the string to the provided address.
"""

import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

browser = webdriver.Chrome()
browser.get('http://www.gmail.com')

emailElem = browser.find_element_by_id('Email')
emailElem.send_keys('My_email@gmail.com')
emailElem.submit()

time.sleep(2)

passwordElem = browser.find_element_by_id('Passwd')
passwordElem.send_keys('My_password_here')
passwordElem.submit()


time.sleep(2)

composeElem = browser.find_element_by_class_name('z0') #this only works half of the time
composeElem.click()

time.sleep(7)

toElem = browser.find_element_by_name("to")
toElem.send_keys('my_other_email@gmail.com')

time.sleep(2)

subjElem = browser.find_element_by_name("subjectbox")
subjElem.send_keys('Test with selenium')

time.sleep(2)

bodyElem = browser.find_element_by_???('???') #this is where I get stuck and not sure what to do here
bodyElem.send_keys('A test email with selenium')

time.sleep(2)

sendElem = browser.find_element_by_link_text('send') #not sure if this is correct too
sendElem.submit()

Answer

I think the easiest way to select elements on a loaded page is to find them by css selector. You can find them in the browser inspector, and then copy their unique css selector (in firefox press inspect element -> copy unique selector). In this case this should work:

browser.find_element_by_css_selector('#\:nw')
Comments