python - 修复: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']")
解决方案
我不知道这个页面是什么,也不知道当你点击一个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
推荐阅读
- python - Python JSON数据加载令人困惑的“预期,分隔符”错误
- sql - 将表列组合成单个字符串(不带 UDF)
- amazon-web-services - 将数据管道转换为代码管道
- java - Intellij Idea 无法解析 ActionEvent 侦听器上的符号
- unity3d - 在按下播放按钮之前将大量数据加载到 Unity 编辑器
- variables - 将变量传递给不同单元的函数
- c# - WPF MVVM - mvvm light 不发送和注册值
- java - Java递归方法一次打印字符串中的一个单词而无需循环
- azure - 如何设置自定义 Azure 403 页面
- git - 使用 DoD 通用访问卡 (GIT) 异地访问 Git - Mac