Instagram爬虫脚本出现IndexError: list index out of range错误求助
问题解决:Instagram粉丝获取脚本的IndexError错误
错误原因分析
你遇到的IndexError: list index out of range,本质是self.driver.find_elements_by_class_name("-nal3")返回的列表为空或长度不足2,导致无法通过索引[1]获取元素。核心问题有两个:
- Instagram前端类名是动态生成的,
-nal3这类临时类名大概率已失效,根本定位不到粉丝按钮 - 硬编码的
time.sleep(5)不可靠,页面可能还没完成动态渲染,元素还未加载就执行了后续操作
修复方案
1. 用显式等待替代固定sleep
显式等待会主动等待目标元素可操作后再执行,比固定等待时间更适配页面加载速度,避免因加载慢导致的元素未找到问题。
2. 更换稳定的元素定位方式
放弃依赖易变的类名,改用结合页面结构和固定属性的XPath定位粉丝按钮,比如通过/followers/这个固定链接后缀来定位。
修改后的代码片段
from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC def get_my_followers(self, username): self.go_to_page(f"https://instagram.com/{username}/") # 显式等待10秒,直到粉丝按钮可点击 wait = WebDriverWait(self.driver, 10) # 通过链接后缀定位粉丝按钮,适配多语言页面 followers_button = wait.until(EC.element_to_be_clickable((By.XPATH, "//a[contains(@href, '/followers/')]"))) followers_button.click() time.sleep(2) my_followers_set = set() initialise_vars = 'elem = document.getElementsByClassName("isgrP")[0]; followers = parseInt(document.getElementsByClassName("g47SY")[1].innerText); times = parseInt(followers * 0.14); followersInView1 = document.getElementsByClassName("FPmhX").length' initial_scroll = 'elem.scrollTop += 500' next_scroll = 'elem.scrollTop += 1500' with open('./jquery-3.3.1.min.js', 'r') as jquery_js: jquery = jquery_js.read() self.driver.execute_script(jquery) self.driver.execute_script(initialise_vars) self.driver.execute_script(initial_scroll) time.sleep(3) next = True while(next): n_li_1 = len(self.driver.find_elements_by_class_name("FPmhX")) self.driver.execute_script(next_scroll) time.sleep(1.5) n_li_2 = len(self.driver.find_elements_by_class_name("FPmhX")) if(n_li_1 != n_li_2): following = self.driver.find_elements_by_xpath("//*[contains(text(), 'Following')]") for follow in following: el = follow.find_element_by_xpath('../..') el = el.find_element_by_tag_name('a') profile = el.get_attribute('href') my_followers_set.add(profile) else: next = False return list(my_followers_set)
额外提醒
- Instagram会频繁更新前端结构,后续如果
isgrP、g47SY这类类名失效,同样需要更换为更稳定的定位方式 - 频繁自动化操作容易触发反爬机制,建议增加随机等待时间,避免账号被限制
- 获取粉丝的粉丝时,可递归调用该函数,但要严格控制请求频率
内容的提问来源于stack exchange,提问作者jimmys
相关产品推荐
相关产品推荐

