All notes
Selenium

Drivers

WebDriver

WebDriver is a component from selenium.

WebDriver is designed to provide a simpler, more concise programming interface in addition to addressing some limitations in the Selenium-RC API.

Selenium specifically provides infrastructure for the W3C WebDriver specification. github.com: selenium.

ChromeDriver

sites.google.com: chromeDriver.

ChromeDriver is a separate executable that WebDriver uses to control Chrome. It is maintained by the Chromium team with help from WebDriver contributors.


import time
from selenium import webdriver

driver = webdriver.Chrome('/path/to/chromedriver')  # Optional argument, if not specified will search path.
driver.get('http://www.google.com/xhtml');
time.sleep(5) # Let the user actually see something!
search_box = driver.find_element_by_name('q')
search_box.send_keys('ChromeDriver')
search_box.submit()
time.sleep(5) # Let the user actually see something!

print(driver.title)
assert 'Google' in browser.title

driver.quit()

brew install chromedriver

FirefoxDriver

Actually, the binary name is "geckodriver":


brew install geckodriver

Use service for large test suite


import time

from selenium import webdriver
import selenium.webdriver.chrome.service as service

service = service.Service('/path/to/chromedriver')
service.start()
capabilities = {'chrome.binary': '/path/to/custom/chrome'}
driver = webdriver.Remote(service.service_url, capabilities)
driver.get('http://www.google.com/xhtml');
time.sleep(5) # Let the user actually see something!

driver.quit()

Best examples



# https://seleniumhq.github.io/selenium/docs/api/py/index.html#drivers
import unittest
from selenium import webdriver

class GoogleTestCase(unittest.TestCase):

    def setUp(self):
        self.browser = webdriver.Firefox()
        self.addCleanup(self.browser.quit)

    def testPageTitle(self):
        self.browser.get('http://www.google.com')
        self.assertIn('Google', self.browser.title)

if __name__ == '__main__':
    unittest.main(verbosity=2)

API

seleniumhq.org.


print(driver.current_url)

Navigation: get(), forward(), back()



driver.get("http://www.google.com")
# Depending on the OS/Browser combination, WebDriver may or may not wait for the page to load.
# To ensure robustness, you need to wait for the element(s) to exist in the page using Explicit and Implicit Waits.

driver.forward()
driver.back()

Find elements



login_form = driver.find_element_by_id('loginForm')
# Or
from selenium.webdriver.common.by import By
element = driver.find_element(by=By.ID, value="coolestWidgetEvah")

content = driver.find_element_by_class_name('content') # By.CLASS_NAME
heading1 = driver.find_element_by_tag_name('h1')
username = driver.find_element_by_name('username')
password = driver.find_element_by_name('password')

continue_link = driver.find_element_by_link_text('Continue')
continue_link = driver.find_element_by_partial_link_text('Conti')

content = driver.find_element_by_css_selector('p.content')

#---------- Find within an element
select = driver.find_element_by_tag_name("select")
allOptions = select.find_elements_by_tag_name("option")
for option in allOptions:
    print "Value is: " + option.get_attribute("value")
    option.click()

XPath vs css_selector

sauceLabs.com.



DIRECT CHILD
XPath: //div/a
CSS: div > a

CHILD OR SUBCHILD
XPath: //div//a
CSS: div a

ID
XPath: //div[@id='example']
CSS: #example

CLASS
XPath: //div[@class='example']
CSS: .example

Get and set values



element.text # retrieve the innerText value

#---------- Select

from selenium.webdriver.support.ui import Select
select = Select(driver.find_element_by_tag_name("select"))
select.deselect_all()
select.select_by_visible_text("Edam")

#---------- Submit

# Call this on an element within a form, WebDriver will walk up the DOM until it finds the enclosing form and then calls submit on that
element.submit()

Run js: execute_script()



# Return a DOM Element, it will be automatically converted to a WebElement object
element = driver.execute_script("return $('.cheese')[0]")

#---------- Pass arguments:
# Finding all the input elements for every label on a page:
labels = driver.find_elements_by_tag_name("label")
inputs = driver.execute_script(
    "var labels = arguments[0], inputs = []; for (var i=0; i < labels.length; i++){" +
    "inputs.push(document.getElementById(labels[i].getAttribute('for'))); } return inputs;", labels)

windows, frames, dialogs



#---------- Window

driver.switch_to.window("windowName")

# Iterate over every open window:
for handle in driver.window_handles:
    driver.switch_to.window(handle)

#---------- Frame

# You can also switch from frame to frame (or into iframes):
driver.switch_to.frame("frameName")

#---------- alert

# You can now accept, dismiss, read its contents or even type into a prompt.
# This interface works equally well on alerts, confirms, and prompts

alert = driver.switch_to.alert
# usage: alert.dismiss(), etc.

cookies

guru99.com: handling with cookies.



driver.add_cookie({'name':'key', 'value':'value', 'path':'/'})
# additional keys that can be passed in are:
# 'domain' -> String,
# 'secure' -> Boolean,
# 'expiry' -> Milliseconds since the Epoch it should expire.

# And now output all the available cookies for the current URL
for cookie in driver.get_cookies():
    print "%s -> %s" % (cookie['name'], cookie['value'])

# You can delete cookies in 2 ways
# By name
driver.delete_cookie("CookieName")
# Or all of them
driver.delete_all_cookies()

# Java?
driver.manage().getCookies();   // Return The List of all Cookies
driver.manage().getCookieNamed(arg0);  //Return specific cookie according to name
driver.manage().addCookie(arg0);   //Create and add the cookie
driver.manage().deleteCookie(arg0);  // Delete specific cookie
driver.manage().deleteCookieNamed(arg0); // Delete specific cookie according Name
driver.manage().deleteAllCookies();  // Delete all cookies

waits

readTheDocs.io: waits.

Two types: explicit and implicit waits. An explicit wait makes WebDriver wait for a certain condition to occur before proceeding further with execution. An implicit wait makes WebDriver poll the DOM for a certain amount of time when trying to locate an element.

Explicit wait



from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.get("http://somedomain/url_that_delays_loading")
try:
    element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "myDynamicElement")))

finally:
    driver.quit()

This waits up to 10 seconds before throwing a TimeoutException unless it finds the element to return within 10 seconds. WebDriverWait by default calls the ExpectedCondition every 500 milliseconds until it returns successfully.

Good example


WAIT_TIME = 200

def getBy(driver, byStr, valStr):
  return WebDriverWait(driver, WAIT_TIME).until( EC.presence_of_element_located((byStr, valStr)) )

if fromLang == 'jp':
  getBy(driver, By.LINK_TEXT, 'オプション').click()
  getBy(driver, By.LINK_TEXT, '言語の変更').click()
else:
  getBy(driver, By.LINK_TEXT, 'Options').click()
  getBy(driver, By.LINK_TEXT, "Change Language").click()

Implicit wait


from selenium import webdriver

driver = webdriver.Firefox()
driver.implicitly_wait(10) # seconds. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object.
driver.get("http://somedomain/url_that_delays_loading")
myDynamicElement = driver.find_element_by_id("myDynamicElement")

Drag and drop



from selenium.webdriver.common.action_chains import ActionChains
element = driver.find_element_by_name("source")
target =  driver.find_element_by_name("target")

ActionChains(driver).drag_and_drop(element, target).perform()

Change UA / profile



# Changing the User Agent
# This is easy with the Firefox Driver:

profile = webdriver.FirefoxProfile()
profile.set_preference("general.useragent.override", "some UA string")
driver = webdriver.Firefox(profile)

profile = webdriver.FirefoxProfile()
profile.native_events_enabled = True
driver = webdriver.Firefox(profile)

Basic

Installation

Ref. In the archive, the XPI file is here: org/openqa/selenium/firefox. To install it by pip:


cd selenium-2.45.0
pacman -Ss pip
sudo pacman -S python-pip
pip install setuptools
sudo python setup.py install

# To solve: FirefoxProfile exception Can't load the profile
pip install -U selenium

Install python and selenium

Install for chrome

Developed in collaboration with the Chromium team, ChromeDriver is a standalone server which implements WebDriver's wire protocol.

You need to download the executable driver from: https://sites.google.com/a/chromium.org/chromedriver/downloads, which is named as "chromedriver.exe".

Then all you need is before creating the driver object use the following (already shown in the correct order):


import os
from selenium import webdriver

chromedriver = "/Users/adam/Downloads/chromedriver"
os.environ["webdriver.chrome.driver"] = chromedriver
driver = webdriver.Chrome(chromedriver)
driver.get("http://stackoverflow.com")
driver.quit()

Maximize window

When the browser window is not large enough for some elements to show, those elements are not clickable. So we would always want to maximize the browser.

Javascript way

StackOverflow.


driver.execute_script("window.moveTo(0,0); window.resizeTo(screen.width, screen.height);")

Driver Options way


ChromeOptions options = new ChromeOptions();
options.AddArgument("--start-maximized");
driver = new ChromeDriver(options);

StackOverflow.


# First instantiate a firefox driver
WebDriver driver = new FirefoxDriver();
# then maximize it
driver.manage().window().maximize();

Zoom in/out

TestingDiaries. The code example below will zoom web page in by 5 levels, zoom out by 1 level and will return to the default zoom level.


public void ZoomExample() throws Exception {
	driver = new FirefoxDriver();
	baseUrl = "https://www.google.co.in";
	driver.get(baseUrl + "/");

	driver.findElement(By.tagName("html")).sendKeys(
			Keys.chord(Keys.CONTROL, Keys.ADD));
	driver.findElement(By.tagName("html")).sendKeys(
			Keys.chord(Keys.CONTROL, Keys.ADD));
	driver.findElement(By.tagName("html")).sendKeys(
			Keys.chord(Keys.CONTROL, Keys.ADD));
	driver.findElement(By.tagName("html")).sendKeys(
			Keys.chord(Keys.CONTROL, Keys.ADD));
	driver.findElement(By.tagName("html")).sendKeys(
			Keys.chord(Keys.CONTROL, Keys.ADD));
	driver.findElement(By.tagName("html")).sendKeys(
			Keys.chord(Keys.CONTROL, Keys.SUBTRACT));
	driver.findElement(By.tagName("html")).sendKeys(
			Keys.chord(Keys.CONTROL, "0"));
}
StackOveflow for python.