如何实现Instagram DM列表第一列自动滚动以完成私信数据抓取
Instagram DM左侧对话列表滚动抓取实现方案
核心思路
你之前用的整页滚动脚本是对document.body执行操作,只要把操作对象替换为左侧对话栏的可滚动容器即可。
实现代码(Python+Selenium)
from selenium import webdriver from selenium.webdriver.common.by import By import time # 前置操作:启动浏览器、登录Instagram并进入DM页面,这部分代码根据你自己的原有逻辑补充即可 driver = webdriver.Chrome() # ... 此处省略登录、进入DM页面的代码 ... # 1. 定位左侧对话列表的滚动容器 # 中文界面aria-label值为「对话」,英文界面改为「Chats」即可 scroll_container = driver.find_element(By.CSS_SELECTOR, 'div[aria-label="对话"]') # 2. 循环滚动直到加载完全部对话 last_scroll_height = driver.execute_script("return arguments[0].scrollHeight", scroll_container) while True: # 滚动到当前容器底部 driver.execute_script("arguments[0].scrollTop = arguments[0].scrollHeight", scroll_container) # 等待新内容加载,网速慢可适当调大等待时长 time.sleep(2) # 获取滚动后容器的高度 new_scroll_height = driver.execute_script("return arguments[0].scrollHeight", scroll_container) # 高度无变化说明所有对话已加载完成 if new_scroll_height == last_scroll_height: break last_scroll_height = new_scroll_height # 3. 提取所有用户名 usernames = [] chat_items = scroll_container.find_elements(By.CSS_SELECTOR, 'span[dir="auto"]') for item in chat_items: text = item.text.strip() if text and text not in usernames: usernames.append(text) print(f"共获取到{len(usernames)}个私信用户:\n{usernames}")
注意事项
- 如果上述选择器无法定位到容器,可打开浏览器开发者工具(F12),用元素选择器点击左侧滚动区域,找到最外层的可滚动元素,复制其CSS选择器替换即可
- 滚动间隔不要设置过短,避免内容未加载完成就触发终止判断
- 不要高频次批量执行该操作,避免触发平台反爬策略导致账号功能受限
内容的提问来源于stack exchange,提问作者shorttriptomars
相关产品推荐
相关产品推荐

