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

Facebook帖子分享信息爬取需求:获取分享者及分享位置

提取Facebook帖子的分享者及分享位置详情

要提取Facebook帖子的分享者及分享位置,你需要调整facebook_scraper的请求选项,并单独解析分享数据。以下是修改后的完整脚本:

from facebook_scraper import get_posts
import pandas as pd

# 初始化存储帖子主数据和分享详情的DataFrame
post_df_full = pd.DataFrame()
share_details_df = pd.DataFrame()

posts = get_posts(
    "RealMadrid", 
    extra_info=True, 
    pages=3, 
    options={
        "comments": True, 
        "shared_username": True,
        "shares": True  # 开启该选项以获取分享数据
    }
)

for post in posts:
    # 处理帖子主数据
    post_entry = post
    fb_post_df = pd.DataFrame.from_dict(post_entry, orient="index").transpose()
    post_df_full = pd.concat([post_df_full, fb_post_df], axis=0)
    
    # 处理分享详情
    post_id = post["post_id"]
    print(f"{post_id} 已获取")
    
    # 提取分享列表(若当前帖子有分享数据)
    shares_data = post.get("shares", {}).get("data", [])
    for share in shares_data:
        # 构建分享详情字典,关联原帖子ID
        share_info = {
            "original_post_id": post_id,
            "shared_by_username": share.get("username"),
            "shared_by_name": share.get("name"),
            "shared_location": share.get("location")  # 部分用户未公开位置时返回空值
        }
        # 转换为DataFrame并合并到总表
        share_df = pd.DataFrame([share_info])
        share_details_df = pd.concat([share_details_df, share_df], axis=0)

# 可选:将数据保存为CSV文件
post_df_full.to_csv("facebook_posts.csv", index=False)
share_details_df.to_csv("facebook_share_details.csv", index=False)

关键说明

  • 核心配置:在options中添加"shares": True,这是获取分享数据的必要配置,否则无法提取分享者信息
  • 数据解析逻辑:每个帖子的分享数据存储在post["shares"]["data"]列表中,遍历该列表可逐个获取分享者的用户名、名称和位置信息
  • 空值兼容:使用字典的.get()方法访问字段,避免因部分用户未公开位置等信息导致代码报错
  • 数据关联:通过original_post_id字段将分享详情与原帖子绑定,方便后续进行关联分析

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 08:35:23