Selenium Examples

From PeformIQ Upgrade
Jump to navigation Jump to search

Back to Selenium Notes

Examples

Checkout:

#!/usr/bin/env python
#--------------------------------------------------------------------------

import time

#--------------------------------------------------------------------------

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys

#--------------------------------------------------------------------------

browser = webdriver.Chrome() # Get local session of firefox

browser.get("http://www.yahoo.com") # Load page

assert "Yahoo!" in browser.title

elem = browser.find_element_by_name("p") # Find the query box

pat = '//div/td[1]'

try:
   xxx = browser.find_element_by_xpath(pat)
except NoSuchElementException, e:
   print"%s - %s" % (e, pat)
   xxx = e.msg

print xxx

elem.send_keys("seleniumhq" + Keys.RETURN)

time.sleep(0.2) # Let the page load, will be added to the API

try:
    browser.find_element_by_xpath("//a[contains(@href,'http://seleniumhq.org')]")
except NoSuchElementException:
    assert 0, "can't find seleniumhq"


cookies = browser.get_cookies()

print cookies

# posn = browser.get_window_position()   # Does not work!

# print "Posn %s" % posn

# size = browser.get_window_size()       # Does not work!

# print "Posn %s" % size

html = browser.page_source

title =  browser.title

print "Title: %s" % title

handles = browser.window_handles

print "Handles: %s" % handles

browser.refresh()

hrefs = browser.find_elements_by_tag_name('a')

# print len(hrefs)

# for href in hrefs:
   # print repr(href)
   # print href.__dict__

time.sleep(2)

browser.back()

time.sleep(2)

browser.close()

#--------------------------------------------------------------------------

# find_element(name)
# find_element_by_class_name(name)
# find_element_by_css_selector(name)
# find_element_by_id(id)
# find_element_by_link_text(link_text)
# find_element_by_Partial_link_text(link_text)
# find_element_by_tag_name(tag_name)
# find_element_by_xpath('//div/td[1]')
#
#
# and the same set as 'find_emements_...
#