while defining user keywords in custom library for web automation,which library should be imported?selenium2library or importing webdriver from selenium.How to use the webdriver to click on some elements.Kindly explain with an example
2 Answers
I have found that inheriting Selenium2Library is usually enough, like this
from Selenium2Library import Selenium2Library
class MySelenium2Library(Selenium2Library):
def my_keyword(self):
my_element = self.get_my_element()
self.click_element(my_element)
In Robot you import this new library
*** Settings ***
Library MySelenium2Library.py
*** Test Cases ***
Test 1
My Keyword
I have not needed webdriver to click elements. I do all my clicking with Selenium2Library click methods like click_element.

- 370,779
- 53
- 539
- 685

- 2,175
- 15
- 20
-
where do you mention the xpath of the element you want to click?Is get_my_element() a function defined in selenium2library? – Sadhana Seervi Feb 10 '16 at 09:10
-
In my example element value was returned by function get_my_element. Element values are same format as Selenium2Library uses. If you have an element with id 'login', you can should be able to just use self.click_element('login'). – Pekka Feb 11 '16 at 06:35
-
how should the web elements be defined in the custom library.element=(by.xpath,"//a[text()='login'] ").will this kind of definition be recognized in custom library – Sadhana Seervi Feb 11 '16 at 06:42
-
Because my example imports Robot Framework's Selenium2Library instead of standard Selenium, element format is a bit different. You do not need to specify by.xpath. You can just use click_element("xpath=//a[text()='login']") – Pekka Feb 11 '16 at 08:18
In most scenarios you do not need to instantiate the webdriver object. Usually you use the webdriver instance that Selenium2Library already has. How you access that instance depends on how you plan on interacting with Selenium2Library. See the "Extending existing test libraries" section in the user guide for options. Each options have pros and cons.
If you inherit Selenium2Library, then you would access the driver via self._current_browser()
.
If you plan on using the Selenium2Library directly instead of inheriting, you would declare both Selenium2Library and your custom libraries. The most convenient way to access the driver is through a private property as demonstrated below.
from robot.libraries.BuiltIn import BuiltIn
class Selenium2LibraryExt(object):
@property
def _s2l(self):
return BuiltIn().get_library_instance('Selenium2Library')
@property
def _driver(self):
return self._s2l._current_browser()
def perform_search(self, criteria):
textbox = self._driver.find_element_by_name('q')
textbox.send_keys(criteria)
textbox.submit()
Test suite file:
*** Settings ***
Test Teardown Close All Browsers
Library Selenium2Library
Library c:/ws/Selenium2LibraryExt.py
*** Test Cases ***
Do a search
Open Browser http://www.google.com/ gc
Perform Search happiness

- 2,344
- 15
- 21