Selenium爬取网站多页面跳转下一页时报StaleElementReferenceException错误如何解决
问题根因
- 触发
StaleElementReferenceException的核心原因是:你仅在首次进入搜索结果页时获取了一次mountRoot元素,点击「下一页」后页面DOM完全刷新,之前存储在内存中的mountRoot及基于它查找到的所有元素引用全部过期失效,第二次循环调用这些失效引用时就会抛出该错误。 - 报错和你使用的循环类型无关,更换while循环不能解决问题。
- 附带的警告是因为高版本Selenium已经弃用
find_element_by_*系列方法,需要替换为标准的find_element写法。
修复后的代码
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time shoe_links = [] page = 1 path = r"C:\Users\redacted\OneDrive\Desktop\chrome driver\chromedriver.exe" driver = webdriver.Chrome(path) driver.get("https://www.myntra.com") # 替换为标准find_element写法 search = driver.find_element(By.CLASS_NAME, "desktop-searchBar") search.send_keys("jordan") search.send_keys(Keys.RETURN) try: while page != 6: # 每次循环重新等待当前页的mountRoot加载完成,获取有效元素引用 mountRoot = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "mountRoot")) ) # 等待商品列表加载完成 item = WebDriverWait(driver,10).until( EC.presence_of_element_located((By.XPATH, "//*[@id='desktopSearchResults']/div[2]/section/ul")) ) liclass = item.find_elements(By.CLASS_NAME, "product-base") for li in liclass: # 提前获取a标签,避免重复查找 a_tag = li.find_element(By.TAG_NAME, 'a') href = a_tag.get_attribute("href").lower() if 'shoe' in href: shoe_links.append(href) # 打印当前收集到的链接 print(f"第{page}页爬取完成,当前总链接数:{len(shoe_links)}") for link in shoe_links: print(link) # 最后一页不需要点击下一页 if page ==5: break # 查找下一页按钮并点击 next_link = WebDriverWait(driver,10).until( EC.element_to_be_clickable((By.LINK_TEXT, "Next")) ) # 点击前先记录当前页的商品列表标识,用于后续等待页面跳转完成 old_item = item next_link.click() # 等待旧的商品列表失效,确认页面已跳转到新页 WebDriverWait(driver,10).until( EC.staleness_of(old_item) ) page +=1 finally: driver.quit()
核心修改点说明
- 把
mountRoot的获取逻辑移到循环内部,每次加载新页面后重新获取有效元素引用 - 每次元素查找都添加显式等待,确保元素处于可用状态再操作
- 点击下一页后添加
staleness_of等待,确认旧页面元素失效后再进入下一轮循环,避免拿到上一页的残留元素 - 替换所有弃用的
find_element_by_*方法为标准的find_element写法,消除警告 - 优化a标签查找逻辑,避免重复查找同一个元素减少报错概率
内容的提问来源于stack exchange,提问作者bob kre
相关产品推荐
相关产品推荐

