所以我有这个项目:它是一个上面有多个 WebElements 的网站。我通过它们的类名找到那些 WebElements(显然它们都有相同的),然后遍历它们以单击它们中的每一个。单击它们后,我必须单击另一个按钮“下一步”。他们中的一些人然后在新标签中打开一个网站(其他人没有)。然后我立即关闭新打开的选项卡,并在收到 StaleElementReferenceException 时尝试遍历下一个元素。
不要误会我的意思,我知道 StaleElementReferenceException 是什么,我只是不知道它为什么会发生。初始网站的 DOM 似乎没有改变,更重要的是:我试图在下一次迭代中达到的 WebElement 仍然是已知的,因此我可以将其打印出来,但不能单击它。
我已尝试通过创建一个新类 CustomElement 来解决此问题,以永久“保存”找到的 WebElement,以便在 DOM 更改后能够访问它们,但这似乎也不起作用。
不管这里有一些代码给你们:
def myMethod():
driver.get("https://initialwebsite.com")
time.sleep(1)
scrollToBottom() #custom Method to scroll to the bottom of the website to make sure I find all webelemnts
ways = driver.find_elements_by_class_name("sc-dYzWWc")
waysCounter = 1
for way in ways:
# print("clicking: " + str(way)) ##this will get executed even if there was a new tab opened in the previous iteration....
driver.execute_script("arguments[0].click();", way)
# print("clicked: " + str(way)) ##...but this won't get executed
try:
text = driver.find_element_by_xpath("/html/body/div[1]/div/div[2]/div/div[1]/div/div[7]/div[2]/div[" + str(entryWaysCounter) + "]/div[1]/div/div/div[1]").text
except:
waysCounter += 1
text = driver.find_element_by_xpath("/html/body/div[1]/div/div[2]/div/div[1]/div/div[7]/div[2]/div[" + str(entryWaysCounter) + "]/div[1]/div/div/div[1]").text
methode = None
#big bunch of if and else statements to give methode a specific number based on what text reads
print(methode)
weiterButton = driver.find_element_by_xpath(
"/html/body/div[1]/div/div[2]/div/div[1]/div/div[7]/div[2]/div[" + str(
entryWaysCounter) + "]/div[2]/div/div/div/div/div/div[2]/button[2]")
try:
driver.execute_script("arguments[0].click();", weiterButton)
except:
pass
if (methode == 19):
time.sleep(0.2)
try:
driver.switch_to.window(driver.window_handles[1])
driver.close()
time.sleep(0.5)
driver.switch_to.window(driver.window_handles[0])
time.sleep(0.5)
except:
pass
waysCounter += 1
time.sleep(0.5)
对于那些好奇的人,这里是我设置的解决方法类:
class CustomElement:
def __init__(self, text, id, location):
self.text = text
self.id = id
self.location = location
def __str__(self):
return str(str(self.text) + " \t" + str(self.id) + " \t" + str(self.location))
def storeWebElements(seleniumElements):
result = []
for elem in seleniumElements:
result.append(CustomElement(elem.text, elem.id, elem.location))
return result
然后我尝试使用 id 并通过 id“重新查找”WebElement(“方式”),但显然被保存的 id 是一个完全不同的 id。
所以我能说什么我真的尽力了,几乎搜索了每个论坛但没有提出一个好的解决方案,我真的希望你能帮我:)
谢谢!