问题描述
因此,我有一个项目:这是一个包含多个WebElement的网站。我通过它们的类名称找到了这些WebElement(显然它们都具有相同的名称),然后遍历它们以单击每个WebElement。单击它们之后,我必须单击另一个按钮“下一步”。然后,其中一些人会在新标签页中打开网站(其他人则没有)。然后,我立即关闭新打开的选项卡,并在收到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(“ way”),但显然保存的id是完全不同的id。
所以我能说我真的尽了最大的努力,搜索了几乎每个论坛,但都没有提出好的解决方案,我真的希望您能为我找到一个:)
谢谢!
解决方法
您要爬网链接吗?如果是这样,那么您要保存目标,而不是元素。
否则,您可以强制链接在新窗口中打开(也许像https://stackoverflow.com/a/19152396/1387701),切换到该位置,解析页面,关闭页面,然后仍然打开原始窗口。