但是这样的实现在运行时会抛出异常:
selenium.common.exceptions.StaleElementReferenceException: Message: u'Element not found in the cache - perhaps the page has changed since it was looked up'
异常的说明已经很明显了:在cache中找不到元素,在元素被找到之后页面变换了。 这就说明,当当前页面发生跳转之后,存在cache中的关于这个页面的元素也被清空了。
因此,我们需要在每次回到原始页面之后对我们感兴趣的a标签元素重新搜索,同时我们又必须接着上次的点击到的元素继续点击。因此我们使用第一种遍历的方法来实现这个for loop:
length = len(driver.find_elements_by_tag_name("a") for i in range(0,length): links = driver.find_elements_by_tag_name("a") link = links[i] if not ("_blank" in link.get_attribute("target") or "http" in link.get_attribute("href")): link.click() driver.back() |
这样,在每次返回页面之后会重新搜索一遍页面上的a元素,然后使用cache中的i继续点击下一个跳转链接。
相关文章: