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

如何用Python+Selenium爬取Instagram粉丝与关注列表?

解决Instagram粉丝/关注列表提取问题

你的代码核心问题是未处理弹窗的滚动加载逻辑,且没有正确定位并提取弹窗内的用户名元素,另外还存在重复初始化Driver、依赖time.sleep导致操作不稳定的问题。以下是修正后的完整方案:

关键修正点

  • 移除重复的Driver初始化,全局仅创建一次实例
  • 用WebDriverWait替代time.sleep,等待元素加载完成再执行操作,避免因页面加载慢导致的定位失败
  • 模拟弹窗内部滚动,加载所有粉丝/关注数据(Instagram弹窗为滚动加载,不滚动只能获取顶部少量用户)
  • 正确定位弹窗内的用户名元素,提取后存入列表
  • 最后对比粉丝和关注列表,筛选出你关注但未回关的用户

修正后的完整代码

import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 配置账号和Driver
username = 'myusername'
password = 'mypassword'
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))
wait = WebDriverWait(driver, 15)  # 全局等待对象,超时15秒

def extract_user_list(box_selector):
    """提取弹窗内的所有用户名"""
    # 点击打开目标弹窗(粉丝/关注)
    box = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, box_selector)))
    box.click()
    
    # 等待弹窗加载完成,获取滚动容器
    popup_container = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '[role="dialog"] ._aano')))
    
    # 模拟滚动加载全部内容
    last_scroll_height = driver.execute_script("return arguments[0].scrollHeight", popup_container)
    while True:
        driver.execute_script("arguments[0].scrollTop = arguments[0].scrollHeight", popup_container)
        time.sleep(2)  # 等待新内容加载
        current_scroll_height = driver.execute_script("return arguments[0].scrollHeight", popup_container)
        if current_scroll_height == last_scroll_height:
            break
        last_scroll_height = current_scroll_height
    
    # 提取所有用户名元素
    user_elements = popup_container.find_elements(By.CSS_SELECTOR, '._aacl._aaco._aacw._aacx._aad7._aade')
    username_list = [user.text for user in user_elements if user.text]
    
    # 关闭弹窗
    close_btn = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, '_abl-')))
    close_btn.click()
    time.sleep(2)
    
    return username_list

def main():
    try:
        # 打开登录页
        driver.get("https://www.instagram.com/accounts/login/")
        
        # 同意Cookie
        cookie_btn = wait.until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Autoriser tous les cookies']")))
        cookie_btn.click()
        
        # 执行登录
        wait.until(EC.presence_of_element_located((By.NAME, 'username'))).send_keys(username)
        wait.until(EC.presence_of_element_located((By.NAME, 'password'))).send_keys(password + Keys.ENTER)
        
        # 跳过保存登录信息提示(如果出现)
        try:
            skip_save = wait.until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Plus tard']")))
            skip_save.click()
        except:
            pass
        
        # 跳过通知权限提示(如果出现)
        try:
            skip_notif = wait.until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Plus tard']")))
            skip_notif.click()
        except:
            pass
        
        # 进入个人主页
        profile_btn = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, f'[alt*="{username}"]')))
        profile_btn.click()
        
        # 获取粉丝列表
        followers_selector = f'[href*="/{username}/followers/"]'
        followers = extract_user_list(followers_selector)
        
        # 获取关注列表
        following_selector = f'[href*="/{username}/following/"]'
        following = extract_user_list(following_selector)
        
        # 筛选未回关用户
        not_following_back = [user for user in following if user not in followers]
        print(f"你关注但未回关的用户:\n{not_following_back}")
        
    finally:
        # 关闭浏览器
        driver.quit()

if __name__ == "__main__":
    main()

注意事项

  • Instagram会频繁更新页面DOM结构,如果选择器失效,需打开浏览器开发者工具(F12)重新定位元素
  • 频繁自动化操作可能触发反爬机制,建议适当延长等待时间,避免短时间内大量请求
  • 如果账号开启两步验证,需手动处理验证步骤

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 05:13:31