selenium.common.exceptions.StaleElementReferenceException 报错原因

原因是点击第二个时已经是新页面,找不到之前页面的元素

 

报错代码段

elem_pic = driver.find_elements_by_xpath("//div[@class='imgpage']/ul/li/div/a/img")
for i in elem_pic:
    elem_url = i.get_attribute("src")
    driver.get(elem_url)
    urlretrieve(elem_url,"m"+str(c)+".jpg")

报错:

selenium.common.exceptions.StaleElementReferenceException: Message: {"errorMessage":"Element does not exist in cache","request":{"headers":{"Accept":"application/json","Accept-Encoding":"identity","Connection":"close","Content-Type":"application/json;charset=UTF-8","Host":"127.0.0.1:50811","User-Agent":"Python http auth"},"httpVersion":"1.1","method":"GET","url":"/attribute/src","urlParsed":{"anchor":"","query":"","file":"src","directory":"/attribute/","path":"/attribute/src","relative":"/attribute/src","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/attribute/src","queryKey":{},"chunks":["attribute","src"]},"urlOriginal":"/session/e23a6270-ad9c-11e7-9d81-eb604b74f70b/element/:wdc:1507627515312/attribute/src"}}

 

只要刷新页面之后重新获取元素就行,不要提前获取一组元素,然后去循环操作每一个元素,这种情况还是获取元素的个数,然后在循环中获取相应位置的元素,在用的时候才去获取

遇到页面有变化的情况,不要去循环元素,去循环个数或者定位方式,在循环中获取元素

posted @ 2017-10-10 18:27  深圳地铁Princess  阅读(1023)  评论(0编辑  收藏  举报