August 19, 2014
Automating menial Browser activity using Selenium
Today I stumbled across a marvelous Framework called Selenium which does browser automation. It lets you programmatically control a web browser session which can be used for automating tests or controlling browser to perform menial works.Here's a small snippet that I put together for myself just to try out selenium's python bindings. Yes, python is the language of my choice currently! :) Selenium binds of various languages are available on their official website at : http://www.seleniumhq.org/
What this script does is open a third party website: way2sms.com, log me in using my username, password and then send a message to any number of my choice. All of this is done programmatically! So all I've to do is fire up a console and enter my username, password, a mobile number and a message and selenium will handle the rest. Of course, this is just an example and one can use this to perform a variety of tasks, boring or otherwise.
from selenium import webdriver from selenium.webdriver.common.keys import Keys from datetime import datetime def send(username, password, mobile, message): driver = webdriver.Firefox() driver.get("http://site25.way2sms.com/content/index.html") driver.find_element_by_id("username").send_keys(username) driver.find_element_by_id("password").send_keys(password) driver.find_element_by_id("loginBTN").send_keys(Keys.RETURN) driver.execute_script("goToMain('s')") driver.execute_script("loadSMSPage('sendSMS')") frame = driver.find_element_by_id("frame") driver.switch_to_frame(frame) driver.find_element_by_id("mobile").send_keys(mobile) driver.find_element_by_id("message").send_keys(message) driver.find_element_by_id("Send").send_keys(Keys.RETURN) driver.switch_to_default_content() driver.close()
You can install selenium python binding using:
sudo easy_install selenium
Since I hacked this together in hurry, it doesn't include any comments but the code should be self explanatory and easy to follow because all it does is find a web element (like an input box or a button) and send it a sequence of keys ( string value of action keys like RETURN ).
Automating tasks on a third party website requires a bit of inspection of web elements and javascripts, even stylesheet at times. This can be done using built-in web inspectors available with most of the modern browsers like Chrome, Firefox. As of now Firebug is the inspector of my choice.
Keep automating!
Subscribe to:
Post Comments (Atom)
ReplyDeleteI am reading your post from some days and they are good this is the first time I comment. So all the best for your future post.
SMO Service Faridabad | Social Media Optimization Company Faridabad