首页 > 解决方案 > 修复:python 循环中的过时元素引用

问题描述

列表中有 100 个项目,persons我想遍历每个项目并单击它们,不包括先前单击的链接。

d = 0
persons = browser.find_elements_by_xpath("//*[@class='i-edit mrs no-text-decoration ember-view']")

for i, person in zip(names[int(d):], persons[int(d):]):    
    person.click()
    time.sleep(1.2)
    fill_in_activate = browser.find_elements_by_xpath("//*[@class='btn btn-default']") # add a 2nd input field
    for btn in fill_in_activate[1:]: #skips the first element it finds
        btn.click() # clicks the 2nd field
           
    # Select and fill out input field
    fill_in = browser.find_elements_by_xpath("//*[@class='form-control ember-view ember-text-field']") 
    first = True
    for field1 in fill_in[3:]: # selecting 4th field
        if first:
            first = False
            field1.send_keys(f'{i[0]}') # fill out information
        else:
            field1.send_keys(f'{i[1]}') # fill out information
    
    # step to save out input into the site        
    save = browser.find_element_by_xpath("//*[@class='btn btn-success']").click() # Saves all inputs      
    time.sleep(2)

    browser.execute_script("window.history.go(-2)")     #browser.back() # goes back to the previous page
    d += 1 # auto-increments d
    time.sleep(5)
    persons = browser.find_elements_by_xpath("//*[@class='i-edit mrs no-text-decoration ember-view']")

标签: pythonseleniumloops

解决方案


我不知道这个页面是什么,也不知道当你点击一个person. 但似乎相当清楚的是,单击会导致页面(可能是同一页面)重新加载,从而呈现剩余的persons陈旧状态。因此,您需要每次通过循环重新获取persons元素。如果我的假设是正确的,那么以下是一个大致的大纲。您可能需要对代码进行其他调整,因为我没有进行初始操作:zip

d = 0
while True:
    persons = browser.find_elements_by_xpath("//*[@class='i-edit mrs no-text-decoration ember-view']")
    if d >= len(persons):
        break
    i = names[d]
    person = persons[d]
    person.click()
    ... # rest of logic
    # end of loop
    d += 1
    

推荐阅读