使用Python获取特定Facebook页面图片:单帖仅获一张图的问题
问题原因与解决方案
核心问题
你代码里遍历的post['image']是单张图片的URL字符串,不是列表。当帖子包含多张图片时,这些图片的URL并不会存在image字段里,而是存放在post['images'](部分旧版本是multiple_images)这个列表字段中。你现在的循环其实是在遍历字符串的每个字符,而非多张图片,自然只能输出一条(甚至可能出现异常)。
修复步骤
先确认字段名:可以在循环里加一行打印,查看当前帖子的所有可用字段:
print(post.keys())运行后你会看到类似
['post_id', 'text', 'image', 'images', ...]的输出,找到存储多图的字段(大概率是images)。修改代码逻辑,兼容单图和多图场景:
替换原有的遍历逻辑,收集当前帖子的所有图片URL后再写入CSV:
import csv import ntpath import os import sys from PIL import Image import urllib.request import pandas as pd from facebook_scraper import get_posts filter="blablabla" for post in get_posts('FB_page',pages=5, cookies= "documents\cookies.json") : if filter in post['text']: # 收集当前帖子的所有图片URL post_images = [] # 加入单图URL(如果存在) if post.get('image'): post_images.append(post['image']) # 加入多图列表里的所有URL(如果存在) if post.get('images'): post_images.extend(post['images']) # 批量写入CSV with open("images7.csv", "a", newline="",encoding="utf-8") as f: writer = csv.writer(f) for img_url in post_images: writer.writerow([img_url])
额外说明
- 用
post.get('字段名')而非直接post['字段名'],可以避免帖子没有对应字段时抛出KeyError。 writerow([img_url])要把URL放在列表里,不然CSV会把字符串拆分成单个字符逐列写入。
内容的提问来源于stack exchange,提问作者sari
相关产品推荐
相关产品推荐

