我正在尝试使用 Selenium 来自动化一个简单的点击和拖动匹配游戏。
游戏中有 12 个方 block (六对匹配的方 block )。网站上的图 block 按顺序列出,因此我只是将所有图 block 存储在一个列表中,然后迭代该列表,单击并拖动每 2 个图 block 以匹配每个元素。两个图 block 在接触后都会在游戏中被删除。
但是,当我运行循环时,它除了抛出陈旧元素异常之外什么也不做。
代码如下:
match_tiles=driver.find_elements(By.CLASS_NAME,"MatchModeQuestionScatterTile")
for i in range(0,12,2):
try:
print("target: "+match_tiles[i].get_attribute("textContent"))
print("destination: "+match_tiles[i+1].get_attribute("textContent"))
actions.click_and_hold(match_tiles[i])
time.sleep(1)
actions.move_to_element(match_tiles[i+1])
time.sleep(1)
actions.release().perform()
except Exception as e:
print(e)
这是输出:
target: Q
destination: q
target: C
destination: c
Message: stale element reference: element is not attached to the page document
(Session info: chrome=76.0.3809.132)
例如,如果 match_tiles
包含 textContent
为
[o,O,r,R,b,B,m,M,h,H,l,L]
target: o
destination: O
target: r
destination: R
target: b
destination: B
Message: stale element reference: element is not attached to the page document
(Session info: chrome=76.0.3809.132)
target: m
destination: M
Message: stale element reference: element is not attached to the page document
(Session info: chrome=76.0.3809.132)
target: h
destination: H
Message: stale element reference: element is not attached to the page document
(Session info: chrome=76.0.3809.132)
target: l
destination: L
Message: stale element reference: element is not attached to the page document
(Session info: chrome=76.0.3809.132)
第一个匹配有效,但之后元素就变得陈旧了。我尝试在每次循环后更新 match_tiles 但无济于事。我添加了一些延迟,希望让页面首先加载,但它似乎也不起作用。
有什么办法可以解决这个问题吗?提前致谢。
最佳答案
由于移动后会被删除,因此移动后该元素将不可用。以下代码可能有效。
match_tiles=driver.find_elements(By.CLASS_NAME,"MatchModeQuestionScatterTile")
for i in range(6):
try:
print("target: "+match_tiles[0].get_attribute("textContent"))
print("destination: "+match_tiles[1].get_attribute("textContent"))
actions.click_and_hold(match_tiles[0])
time.sleep(1)
actions.move_to_element(match_tiles[1])
time.sleep(1)
actions.release().perform()
except Exception as e:
print(e)
match_tiles=driver.find_elements(By.CLASS_NAME,"MatchModeQuestionScatterTile")
关于python - 即使更新后列表中的元素也已过时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57799796/