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

使用Selenium爬取Instagram Reels点赞数时数据不更新的问题求助

解决Instagram Reels点赞数重复获取的问题

核心原因

你遇到的问题本质是滑动后页面未完全加载就获取元素,或者复用了已失效的元素对象,导致每次读取的都是第一次加载的DOM节点值。

具体解决步骤

  • 每次循环重新定位元素:不要把点赞元素的定位代码放在循环外,每次滑动后必须重新查找元素,避免复用已过期的DOM引用。
  • 用显式等待替代固定休眠:滑动后强制等待新Reels加载完成,不要依赖time.sleep(),改用WebDriverWait等待点赞元素可交互或出现。
  • 修正元素定位逻辑:Instagram的class是动态生成的,优先用aria-label等语义化属性定位,比如中文界面下,点赞数的元素会包含aria-label="赞,xxx次",可以用XPATH匹配这个属性。
  • 模拟真实用户滑动:不要用普通的页面滚动,要针对Reels容器做垂直滑动,确保触发Reels的切换逻辑。

示例代码片段

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import StaleElementReferenceException
import time
import random

driver = webdriver.Chrome()
driver.get("https://www.instagram.com/reels/")
# 此处可添加登录逻辑(若需要)

wait = WebDriverWait(driver, 10)
count = 0
max_reels = 50  # 目标收集的Reels数量

while count < max_reels:
    try:
        # 等待点赞元素出现并重新定位
        like_element = wait.until(
            EC.presence_of_element_located(
                (By.XPATH, "//span[contains(@aria-label, '赞')]")
            )
        )
        # 提取点赞数并处理格式
        like_label = like_element.get_attribute("aria-label")
        like_count = like_label.split(",")[1].replace("次", "").strip()
        # 处理K/M格式(如165K转为165000)
        if "K" in like_count:
            like_count = int(float(like_count.replace("K", "")) * 1000)
        elif "M" in like_count:
            like_count = int(float(like_count.replace("M", "")) * 1000000)
        print(f"第{count+1}条Reels点赞数:{like_count}")
        
        # 模拟用户向上滑动切换Reels
        reels_container = wait.until(
            EC.presence_of_element_located((By.TAG_NAME, "article"))
        )
        action = ActionChains(driver)
        action.click_and_hold(reels_container).move_by_offset(0, -800).release().perform()
        
        count +=1
        # 随机休眠避免触发反爬
        time.sleep(random.uniform(1.5, 3))
        
    except StaleElementReferenceException:
        # 元素失效时跳过本次循环,重新定位
        continue
    except Exception as e:
        print(f"出错:{str(e)}")
        break

driver.quit()

额外注意事项

  • Instagram有反爬机制,操作频率不要过高,建议使用随机休眠时间。
  • 如果是英文界面,把XPATH里的'赞'换成'likes'即可。
  • 若遇到元素定位失败,直接用浏览器开发者工具查看当前Reels点赞元素的aria-label属性,调整XPATH匹配规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 23:46:09