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

如何用Python实现Facebook视频下载?为fbchat开发的Messenger机器人添加该功能

解决Facebook Messenger机器人(基于fbchat)的视频下载问题

方法1:直接解析视频页面HTML提取源地址

Facebook视频页面的源码中会嵌入不同画质的视频源链接,可通过请求页面并解析HTML来获取,无需依赖第三方API。

实现步骤:

  • 用requests库请求视频页面,需添加浏览器UA头避免被拦截
  • 处理fb.watch短链接,先跳转获取真实视频页面URL
  • 用正则匹配页面中的高清(hd_src)和标清(sd_src)视频地址

示例代码:

import requests
import re
from fbchat import Client
from fbchat.models import Message

class VideoBot(Client):
    def onMessage(self, author_id, message_obj, thread_id, thread_type, **kwargs):
        self.markAsDelivered(thread_id, message_obj.uid)
        self.markAsRead(thread_id)

        # 识别Facebook视频URL
        msg_text = message_obj.text
        if not ("facebook.com/watch" in msg_text or "fb.watch" in msg_text):
            return

        # 解析短链接
        if "fb.watch" in msg_text:
            resp = requests.head(msg_text, allow_redirects=True)
            video_url = resp.url
        else:
            video_url = msg_text

        # 请求视频页面,模拟浏览器
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"
        }
        page_html = requests.get(video_url, headers=headers).text

        # 提取视频源链接
        hd_link = re.search(r'"hd_src":"(.*?)"', page_html)
        sd_link = re.search(r'"sd_src":"(.*?)"', page_html)

        reply_lines = []
        if hd_link:
            reply_lines.append(f"高清画质: {hd_link.group(1).replace('\\', '')}")
        if sd_link:
            reply_lines.append(f"标清画质: {sd_link.group(1).replace('\\', '')}")

        reply = "\n".join(reply_lines) if reply_lines else "无法提取有效视频链接,请检查URL是否正确。"
        self.send(Message(text=reply), thread_id=thread_id, thread_type=thread_type)

# 初始化机器人(替换为你的账号密码)
client = VideoBot("your_fb_email", "your_fb_password")
client.listen()

方法2:借助Facebook Graph API(需权限)

如果能获取视频的video_id,可通过Graph API合法获取视频源,但需要申请对应权限(如user_videos或page_videos)及访问令牌。

核心代码片段:

def get_video_links_via_graph(video_id, access_token):
    api_endpoint = f"https://graph.facebook.com/v18.0/{video_id}?fields=source,format&access_token={access_token}"
    resp = requests.get(api_endpoint).json()
    
    if "source" in resp:
        return f"直接下载: {resp['source']}"
    elif "format" in resp:
        return "\n".join([f"{item['quality']}: {item['source']}" for item in resp['format']])
    else:
        return "API请求失败,请检查权限或video_id"

注意事项

  • Facebook可能会调整页面结构,正则表达式需定期适配更新
  • 频繁请求易触发反爬,建议添加请求间隔或使用代理
  • Graph API的权限申请需符合Facebook平台政策,避免违规

内容的提问来源于stack exchange,提问作者Saif Abdullah Khan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 11:50:06