无法绕过 Stale Element 参考。我认为innerArticles 数组有问题,因为它控制整个for 循环。在我明确刷新后,我得到了陈旧的元素异常。
基本上我希望页面保持刷新,直到页面上出现 SubItems xpath 中的“文本”。因为我不知道这什么时候会发生,所以我需要开始并继续重新加载。
任何帮助表示赞赏。
代码:
innerArticles = driver.find_elements_by_xpath("//div[@class='inner-article']")
for links in innerArticles:
print('inFor')
SubItems = links.find_elements_by_xpath("//a[text()='Text']")
iterator = 0
if len(SubItems) < 1:
print('Sub < 1')
while iterator < 5:
print('While', iterator)
time.sleep(1) # sleep 1 seconds to refresh again
iterator = iterator + 1 # iterate
driver.refresh() # refresh
SubItems = links.find_elements_by_xpath("//a[text()='Text']")
break
if len(SubItems) > 0:
print('break')
break
if len(SubItems) > 0:
print('SecondIf')
if links.text.startswith('SText') and links.text.endswith('SText'):
links.click()
当您进行显式刷新时,链接对象将不再有效,并将抛出StaleElementReferenceException
. 刷新后您应该再次获取该元素。您可以尝试以下操作:
innerArticles = driver.find_elements_by_xpath("//div[@class='inner-article']")
for i in range(len(innerArticles)):
print('inFor')
SubItems = driver.find_elements_by_xpath("//div[@class='inner-article']")[i].find_elements_by_xpath("//a[text()='Text']")
iterator = 0
if len(SubItems) < 1:
print('Sub < 1')
while iterator < 5:
print('While', iterator)
time.sleep(1) # sleep 1 seconds to refresh again
iterator = iterator + 1 # iterate
driver.refresh() # refresh
SubItems = driver.find_elements_by_xpath("//div[@class='inner-article']")[i].find_elements_by_xpath("//a[text()='Text']")
break
if len(SubItems) > 0:
print('break')
break
if len(SubItems) > 0:
print('SecondIf')
links = driver.find_elements_by_xpath("//div[@class='inner-article']")[i]
if links.text.startswith('SText') and links.text.endswith('SText'):
links.click()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句