Selenium is a so great tool to make web ui test, in some cases, we have to make it work with some ajax autocomplete like jquery ui autocomplete.
First you need to understand how the autocomplete work. Most plugin will create a ul which contain data get from the server by ajax, and insert the ul into the body, then display it for user to click
by mouse or enter
by keydown.
When the page load, you can see the ul has no children
Then I type in some word in the input to make the plugin make ajax query
As you can see, plugin use the data returned from server create li in ul element and display it, so how to make Selenium wait for ajax complete? Selenium provide WebDriverWait which can wait for something done.
The next thing to do is to choose the item, user can click
or enter
to choose the item, so there are at least two ways to make selenium work with autocomplete
#first set value to input to make ajax start
self.wd = CustomWebDriver()
self.wd.find_element_by_id('input')
#selenium will wait until it find li in ul, outtime is 5
WebDriverWait(self.wd , 5).until(
lambda driver :
driver.find_elements_by_xpath(
r"//ul[@id='ui-id-1']/li"
)
)
#after ajax complete, simulate click operation
self.wd.find_element_by_xpath("//ul[@id='ui-id-1']/li[1]/a").click()
The code above need to be modified when you use it because some detail between plugin is not same
You can also choose enter
to choose the item, all roads lead to rome.