我正在尝试使用Selenium来自动化一个简单的单击并拖动匹配游戏。
在游戏中,有12个图块(六对匹配的图块)。网站上的图块是按顺序列出的,因此我只是将所有图块存储在列表中,然后遍历列表,单击并拖动每2个图块以匹配每个元素。触摸后,两个图块都会在游戏中被删除。
但是,当我运行循环时,除了抛出过时的元素异常外,它什么也不做。
代码如下:
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无济于事。我增加了一些延迟,希望首先让页面加载,但它似乎也不起作用。
有什么办法可以解决这个问题?预先感谢。
答案 0 :(得分:1)
由于移动后将其删除,因此该元素在移动后将不可用。以下代码可能有效。
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")
答案 1 :(得分:0)
我认为也许我找到了根本原因 如果有12个图块,则根据以下声明
match_tiles=driver.find_elements(By.CLASS_NAME,"MatchModeQuestionScatterTile")
我相信12 elements
的返回列表
但是问题是,当您第一次拖放第一个匹配的图块时,两个图块都消失了,现在您有了10 tiles left
,并且您仍在迭代不存在的list of 12 elements
,因此您将stale element exception
,因为您要尝试迭代用户界面中甚至不存在的此类元素。
要克服此问题,您需要做的是尝试在循环中每次都找到一个元素列表,并据此创建逻辑。