我的脚本会刮擦页面,如果根据我的要求有新元素,它会点击按钮,当只有一个元素一切都很完美但问题是当它点击按钮时,会打开一个新页面。因此,如果有多个元素,我需要返回上一页继续处理。
我确实尝试了browser.back()
,但当它返回上一页时,它不记得这些元素,并按照我的预期给出了这个错误:selenium.common.exceptions.StaleElementReferenceException: Message: Element not found in the cache - perhaps the page has changed since it was looked up
的行{{1}这是第一行,我让它识别新元素。
我还尝试通过点击按钮打开一个新的标签/窗口,但按钮没有此功能,因为它是javascript。有没有办法解决这个问题?
答案 0 :(得分:1)
根据例外
selenium.common.exceptions.StaleElementReferenceException: Message: Element not found in the cache - perhaps the page has changed since it was looked up
我们开始知道,无论何时页面加载webdriver都会丢失对之前保存的webelements的引用。
因此,最好的方法是在java预期中调用预定义的关键字/方法时动态传递定位器,以便webdriver在该实例中查找该Web元素并执行操作。
有些时候我们可能会在循环Web元素列表中收到相同的异常,因为在循环中由于动作webdriver可能会松散引用,所以在循环中我们还需要指定定位器以使其不会失败。例如,如果我需要点击链接,我会给出这样的路径" //一个[" + i +"]"
谢谢你, 穆拉利
答案 1 :(得分:1)
first_window_handler = driver.current_window_handle
driver.find_element_by_css_selector("body").send_keys(Keys.CONTROL + 't')
second_window_handler = driver.window_handles[1]
# from second page
driver.switch_to.window(second_window_handler)
element_from_second = driver.find_element_by_css_selector('something')
# from first page
driver.switch_to.window(first_window_handler)
element_from_first = driver.find_element_by_css_selector('something else')
现在您可以在窗口之间切换,元素仍然可以互动