Message: stale element reference: element is not attached to the page document

背景:获取一组按钮,数量不确定,得到所有按钮A之后使用get_attribute(“innerHTML”)获取xpath并用A.find_element来获取每个按钮
代码如下:

el_pager = driver.find_element(by=By.XPATH,value="")
s = el_pager.get_attribute("innerHTML")
page_number = get_pages(s)
for each_page in page_number:
    el_pager.find_element(by=By.XPATH, value="li[%s]" % each_page).click()
    time.sleep(5)
    all_batch = driver.find_element(by=By.XPATH,value="")
    time.sleep(5)
    print(all_batch.get_attribute("innerHTML"))
    time.sleep(5)

报错:Message: stale element reference: element is not attached to the page document
查询:网上大多都是说网页元素未刷新,导致获取失败,强制sleep,没有用
根本原因:跳转之后所引用的元素已从 DOM 结构中删除,需要重新生成一个webdriver
修改之后:

el_pager = driver.find_element(by=By.XPATH,value="")
s = el_pager.get_attribute("innerHTML")
page_number = get_pages(s)
for each_page in page_number:
    el_pager = driver.find_element(by=By.XPATH,
                                   value="")
    el_pager.find_element(by=By.XPATH, value="li[%s]" % each_page).click()
    time.sleep(5)
    all_batch = driver.find_element(by=By.XPATH,
                                    value="")
    time.sleep(5)
    print(all_batch.get_attribute("innerHTML"))
    time.sleep(5)

你可能感兴趣的:(python,自动化测试,javascript,前端,python)