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

Selenium爬取Instagram关注者列表加载不全及超时问题求助

解决Instagram关注者列表加载不全的问题

问题根源分析

  1. 绝对XPATH极度脆弱:你用的/html/body/...这种全路径定位,只要Instagram页面结构微调就会失效;定位用户名的层级过于冗余,出错概率极高。
  2. 等待逻辑错误:你等待的是单个用户名元素,但该元素可能初始就存在,无法触发"等待新元素加载"的逻辑,导致滚动后没等新关注者加载就提前结束循环。
  3. 滚动逻辑不完善:直接滚到面板底部后立刻取高度,此时新元素可能还在加载中,高度未变化,循环便提前终止。

修复后的代码方案

from selenium import webdriver
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

# 假设已完成登录并打开目标用户的关注者弹窗
followers_panel = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.XPATH, '//div[@role="dialog"]//div[@class="_aano"]'))
)

target_follower_count = 54
list_of_followers = []

while len(list_of_followers) < target_follower_count:
    # 获取当前已加载的所有用户名元素
    follower_elements = followers_panel.find_elements(By.XPATH, './/div[@class="_ab8y _ab94 _ab97 _ab9f _ab9k _ab9p _abcm"]')
    
    # 提取未添加过的用户名
    for elem in follower_elements[len(list_of_followers):]:
        username = elem.text.strip()
        if username:
            list_of_followers.append(username)
    
    # 已加载完成则跳出循环
    if len(list_of_followers) >= target_follower_count:
        break
    
    # 滚动到最后一个已加载元素,精准触发懒加载
    driver.execute_script('arguments[0].scrollIntoView(true);', follower_elements[-1])
    # 给Instagram留足加载时间,匹配懒加载节奏
    time.sleep(1.5)

print(f"成功获取{len(list_of_followers)}个关注者:")
print(list_of_followers)

关键改进点

  • 改用相对定位:
    • 关注者面板用//div[@role="dialog"]//div[@class="_aano"]定位(这是Instagram关注者弹窗的滚动区域类,相对稳定)
    • 用户名直接定位面板下的目标class元素,无需绕多层级
  • 基于元素数量循环:不再硬编码循环次数,通过已加载用户名数量判断是否完成,更可靠
  • 精准滚动触发加载:滚动到最后一个已加载元素的位置,比直接滚到底部更易触发懒加载
  • 添加合理等待:每次滚动后留1.5秒加载时间,避免频繁操作导致加载失败或触发反爬

额外注意事项

  • Instagram的class名可能更新,若后续_ab8y...类失效,直接用浏览器开发者工具重新查看用户名元素的最新class即可
  • 不要频繁快速滚动,容易触发Instagram反爬机制,导致账号受限
  • 若仍有加载问题,可适当延长time.sleep时长,或添加WebDriverWait等待新元素出现的逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 23:35:18