How to test autocomplete using selenium and Python

2020-08-04 04:49发布

问题:

I've been writing a couple of tests using selenium for my website. However, I've not found a way to test an input textfield that is filled by auto completion. As an example, I want to select one of the locations that is displayed in an auto-complete list dropdown.

This is what I have so far:

driver.find_element_by_id("id_location_0").send_keys("Free City")
driver.find_element_by_id("ui-active-menuitem").click()

How is Auto-complete/Auto-suggest testing achieved in selenium using Python?

NOTE: Google search is a good example of what I'm trying to do.

回答1:

It really depends on the application but the general way to go is either:

Look at what type of elements are shown in the auto complete list, in the case of google it is spans in a table, so you would do something like

driver.find_element_by_css_selector("css selector that matches all the auto complete suggestions)

then iterate through them until you find the one/ones you expect.

THe other option for google is to use the keydown events to select an option and the key enter to confirm that as your choice



回答2:

The following code worked for me:

driver.find_element_by_id("id_location_0").send_keys("Free City")
element_to_hover_over = driver.find_element_by_css_selector("ul.ui-autocomplete > :first-child ")
hover = ActionChains(driver).move_to_element(element_to_hover_over)
hover.perform()
driver.find_element_by_id("ui-active-menuitem").click()

I'm sure this can be optimized in some way.