Iterating through the recovered list of items

I have : two lists of unused and used items. I have to pass the exact elements (the element can be dragged with a double click or click the + click button, than it disappears from the "unused elements" and appears in the "used elements") from the first to the second. Found that the first list is reloading every time I move an item.

for x in range(0, len(offers)):
    try:
        if "21796" in offers[x].get_attribute('text'):
            ActionChains(app.driver).double_click(offers[x]).perform()
            offers = app.driver.find_elements_by_css_selector('select[name="unused_offers[]"]>option')
    except IndexError:
        break

      

So, I am looping through the range of length of the list of initial sentences and two problems arise:

1) If I do not re-request the list of "offers", I will receive StaleElementException

2) If I do this, I will be out of range of the initial suggestions list, because each "suggestion" list of each iteration gets shorter.

I decided to go through the 2) way and just handle the exception IndexError

.

The question is : is there a better way to iterate over a list that gets shorter than the iteration range?

I tried it too

ActionChains(app.driver).key_down(Keys.CONTROL, offers[x]).click(offers[x]).key_up(Keys.CONTROL, offers[x]).perform()

      

Looped for the list of exceptions repeatedly, but there was a loop of questions just clicking the items one by one (it looks like CTRL was not actually executed.

+3


source to share


1 answer


I would do an "infinite" loop, find the sentence at each iteration, and exit the loop as soon as the sentence is not found ( NoSuchElementException

exception). Implementation:



from selenium.common.exceptions import NoSuchElementException

while True:
    try:
        offer = app.driver.find_element_by_xpath('//select[@name="unused_offers[]"]/option[contains(@text, "21796")]')
    except NoSuchElementException:
        break

    ActionChains(app.driver).double_click(offer).perform()

      

+2


source







All Articles