You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Selenium Python翻页提取链接?附元素过时引用报错

问题解决:Selenium捕获链接时出现StaleElementReferenceException

错误原因

你遇到的StaleElementReferenceException是因为提前获取的元素集合classe在页面跳转后失效了。当调用driver.get()跳转到新页面时,浏览器会重新渲染DOM,之前找到的元素引用就和当前页面文档脱节,再访问这些元素的text属性就会报错。

修复后的代码

把查找元素的代码放到分页循环内部,每次加载新页面后重新定位元素,同时用显式等待替代固定sleep提升稳定性:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

links = []

for pages in range(2,6):
    driver.get(f"https://www.xxxx.com.br/painel/my-links?page={pages}&items=6&q=&startDate=&endDate=&popular=0")
    # 显式等待元素加载完成,替代固定sleep
    WebDriverWait(driver, 10).until(
        EC.presence_of_all_elements_located((By.XPATH, "//*[@class='LinksShowcase_UrlContainer__kMj_n']/p"))
    )
    # 每次新页面都重新查找元素
    classe = driver.find_elements(By.XPATH, "//*[@class='LinksShowcase_UrlContainer__kMj_n']/p")
    
    for i in classe:
        links.append(i.text)
        print(links)

额外优化建议

  • 避免使用固定sleep(),显式等待会根据元素实际加载情况等待,效率更高也更稳定
  • 如果链接是a标签的href属性,直接用i.get_attribute('href')获取会比取text更准确(从HTML截图看,链接应该在p标签内的a元素中,可将XPath调整为//*[@class='LinksShowcase_UrlContainer__kMj_n']/p/a,再用get_attribute('href')提取)

内容的提问来源于stack exchange,提问作者Felipe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 05:35:37