Reputation: 189
is it possible to get one 'general xpath' for several xpaths by using a python dictionary? In a locators class I want to locate all the elements in a formula to automatically type in data (for automation testing). And in the XPATH, all that changes per field is just input'number+1' each time. So I created this dictionary in python:
class CreateLabLocators(object):
formulaDictionary = {"labname":12,
"city":13,
"state":14,
"zipcode":15,
"street":16,
"number":17,
"country":18,
"website":19,
"phone":20,
"fax":21,
}
Is it possible to use the key and the value of the dictionary to have a locator for each field? So instead of this:
labname = (By.XPATH, "//input[@id='__input12-inner']")
city = (By.XPATH, "//input[@id='__input13-inner']")
state = (By.XPATH, "//input[@id='__input14-inner']")
zipcode = (By.XPATH, "//input[@id='__input15-inner']")
street = (By.XPATH, "//input[@id='__input16-inner']")
number = (By.XPATH, "//input[@id='__input17-inner']") (etc...)
Have something more general. How would I implement this? So that if I want to call the locator outside the class, I should be able to do it in a way like...
find_element(*CreateLabLocators.city).send_keys("abc")
find_element(*CreateLabLocators.zipcode).send_keys("123")
and so on. On a side note, I am using Python 2.7.
Upvotes: 0
Views: 2108
Reputation: 52685
In your exact case you can simply do following:
for index in range(12, 22):
locator = (By.XPATH, "//input[@id='__input%s-inner']" % index)
# do something with locator
Or if you want to use values from dictionary:
for item in formulaDictionary:
locator = (By.XPATH, "//input[@id='__input%s-inner']" % formulaDictionary[item])
# do something with locator
Upvotes: 1
Reputation: 125
You could you do something like this -
def xpath_builder(which_one):
first_half = r"//input[@id='__input"
second_half = r"-inner']"
return (first_half + formulaDictionary[which_one] + second_half)
your_element = driver.find_element_by_xpath(xpath_builder(city))
Upvotes: 1