Navigating
Navigate a link with WebDriver:
driver.get("http://www.google.com")
1.Interacting with the page
Element define:
<input type="text" name="passwd" id="passwd-id" />
Find:
element = driver.find_element_by_id("passwd-id")
element = driver.find_element_by_name("passwd")
element = driver.find_element_by_xpath("//input[@id='passwd-id']")
element.send_keys("some text")
element.send_keys(" and some", Keys.ARROW_DOWN)
element.clear()
2.Filling in forms
**SELECT tags:**
element = driver.find_element_by_xpath("//select[@name='name']") //find the first “SELECT” element on the page
all_options = element.find_elements_by_tag_name("option")
for option in all_options:
print("Value is: %s" % option.get_attribute("value"))
option.click() //cycle through each of its OPTIONs in turn, printing out their values, and selecting each in turn
**“Select” class: **
from selenium.webdriver.support.ui import Select
select = Select(driver.find_element_by_name('name'))
select.select_by_index(index)
select.select_by_visible_text("text")
select.select_by_value(value)
select = Select(driver.find_element_by_id('id'))
select.deselect_all()
select = Select(driver.find_element_by_xpath("//select[@name='name']"))
all_selected_options = select.all_selected_options
options = select.options //To get all available options:
# Assume the button has the ID "submit" :)
driver.find_element_by_id("submit").click()
element.submit()
3.Drag and drop
element = driver.find_element_by_name("source")
target = driver.find_element_by_name("target")
from selenium.webdriver import ActionChains
action_chains = ActionChains(driver)
action_chains.drag_and_drop(element, target).perform()
4.Moving between windows and frames
“switch_to_window” method:
driver.switch_to_window("windowName")
How to know the window’s name? Page Source:
<a href="somewhere.html" target="windowName">Click here to open a new window</a>
for handle in driver.window_handles:
driver.switch_to_window(handle)
driver.switch_to_frame("frameName") //swing from frame to frame (or into iframes)
driver.switch_to_frame("frameName.0.child") //access subframes by separating the path with a dot, and you can specify the frame by its index
driver.switch_to_default_content() //come back to the parent frame
5.Popup dialogs
Access the alert with the following:
alert = driver.switch_to_alert() //Return the currently open alert object
6.Navigation: history and location
driver.get("http://www.example.com")
driver.forward() //move backward
driver.back() //move forward
7.Cookies
# Go to the correct domain
driver.get("http://www.example.com")
# Now set the cookie. This one's valid for the entire domain
cookie = {‘name’ : ‘foo’, ‘value’ : ‘bar’}
driver.add_cookie(cookie)
# And now output all the available cookies for the current URL
driver.get_cookies()