All notes
Selenium

Drivers

WebDriver

WebDriver is a component from 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

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()

FirefoxDriver

Actually, the binary name is "geckodriver":


brew install geckodriver

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

Find elements



heading1 = driver.find_element_by_tag_name('h1')
content = driver.find_element_by_class_name('content')
content = driver.find_element_by_css_selector('p.content')

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

username = driver.find_element_by_name('username')
password = driver.find_element_by_name('password')

login_form = driver.find_element_by_id('loginForm')

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

cookies

guru99.com: handling with cookies.


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")

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.