如何防止过时的元素引用并使WebElement在selenium中自我更新



我是一个处理python和selenium的新手,一周前刚刚开始,所以请原谅我的代码一团糟。我试图从这个网站中带有标记名的元素中提取所有的"structure_id"one_answers"d"信息,并将它们分别存储在一个单独的svg文件中。以下是我遇到问题的代码片段:

for number in range(1,106):
try:
element = WebDriverWait(driver, 10).until(
EC.presence_of_all_elements_located((By.ID, 'master_group'))
)
selected = driver.find_element_by_class_name('simstripImgSel')
driver.get(driver.current_url)
paths = driver.find_elements_by_tag_name('path')

for path in paths:
while True:
try:
structure = path.get_attribute('structure_id')
d = path.get_attribute('d')
break
except Exception as e:
print(e)
paths = driver.find_elements_by_tag_name('path')
continue
if structure != None:
print('Attributes copied.')
for word, initial in data.items():
structure = structure.replace(word,initial)
filepath = Path('C:\Users\justs\Downloads\Ordered_svgs\slice'+str(number)+'\'+str(structure)+'.svg')
if filepath.is_file():
text = open('C:\Users\justs\Downloads\Ordered_svgs\slice'+str(number)+'\'+str(structure)+'.svg','r+')
rep = text.read()
rep = rep.replace('</svg>','<path id="')
text.close()
os.remove('C:\Users\justs\Downloads\Ordered_svgs\slice'+str(number)+'\'+str(structure)+'.svg')
time.sleep(0.2)
text = open('C:\Users\justs\Downloads\Ordered_svgs\slice'+str(number)+'\'+str(structure)+'.svg','w+')
text.write(rep+str(structure)+'" d="'+str(d)+'"></path></svg>')
text.close()
print('File '+str(structure)+' modified in slice '+str(number)+'!')
else:
svg = open('C:\Users\justs\Downloads\Ordered_svgs\slice'+str(number)+'\'+str(structure)+'.svg','w+')
svg.write('<svg id="the_svg_wrapper" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg"><path id="'+str(structure)+'" d="'+str(d)+'"></path></svg>')
svg.close()
print('File '+str(structure)+' made in slice '+str(number)+'!')
selected.send_keys('F')
paths = 0
print()

except Exception as e:
print('Error.')
print(e)
break
print('Done!')
driver.quit()

这对第一页很好,但我需要提取所有106页的路径,在按一次"F"(移动到下一页(后,我在structure = path.get_attribute('structure_id')行得到一个过时的元素引用。起初,我认为加载路径需要一些时间,因此产生了while循环,但到了第二页,它就被没完没了的过时元素引用卡住了。

显式等待或刷新页面也不起作用,我怀疑driver.find_element_by_class_nameWebElement根本没有更新(当我在转到下一页后刷新页面时,我提取的文件最终与第一页相同,而且我在第5页之前得到了一个过时的元素引用(。我该如何解决此问题?感谢您的帮助!

您循环url,使其进入第1页。

driver.get('http://atlas.brain-map.org/atlas?atlas=265297126#atlas=265297126&plate=102339919&structure=10155&x=42480&y=16378&zoom=-7&resolution=124.49&z=2')
for i in range(1,106):
try:
paths=WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located((By.TAG_NAME, "path")))   
for path in paths:
structure = path.get_attribute('structure_id')
d = path.get_attribute('d')
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CLASS_NAME, "simstripImgSel"))).send_keys("F")
time.sleep(0.5)
except Exception as e:
print(e)

导入

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC

最新更新