Python返回上一页并记住元素

Python back to previous page with remembering the elements

本文关键字:元素 返回上一页 Python      更新时间:2023-09-26

我的脚本抓取页面,如果根据我的要求有一个新元素,它会单击按钮,当只有一个元素时,一切都很完美,但问题是当它单击按钮时,会打开一个新页面。所以若有不止一个元素,我需要回到上一页继续处理。

我确实尝试了browser.back(),但当它回到上一页时,它不记得元素,并如我所料给出了这个错误:selenium.common.exceptions.StaleElementReferenceException: Message: Element not found in the cache - perhaps the page has changed since it was looked up的行if len(css(".Total", parent=new, nowait=True)) > 0:是第一行,我让它识别新元素。

我还试图通过单击按钮打开一个新的选项卡/窗口,但按钮没有这个功能,因为它是javascript。有没有有效的方法来解决这个问题?

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')

现在您可以在窗口之间切换,并且元素仍然是可交互的

根据异常

  selenium.common.exceptions.StaleElementReferenceException: Message: Element not found in the cache - perhaps the page has changed since it was looked up

我们知道,每当页面加载webdriver时,就会丢失对之前保存的webelement的引用。

因此,最好的方法是在调用java-prospective中预定义的关键字/方法时始终动态传递定位器,以便webdriver在该实例中查找该web元素并执行操作。

有时,我们可能会在web元素的循环列表中收到相同的异常,因为在循环中,由于操作,webdriver可能会失去引用,所以在循环中我们还需要指定定位器,这样它就不会失败。例如,如果我需要点击链接,我会给出这样的路径"//a["+i+"]"

谢谢,Murali