You need to enable JavaScript to run this app. Python中如何按条件筛选对象列表 保留text字段包含指定字符串的元素
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何按条件筛选对象列表 保留text字段包含指定字符串的元素

实现方案

方案1:爬取时直接筛选(推荐,节省内存空间)

爬取过程中直接判断内容是否符合要求,符合条件才存入结果列表,不需要额外存储全量爬取数据:

from facebook_scraper import get_posts

listposts = []
target_key = "abc"
for post in get_posts("myhealthkkm", pages=1):
    # 先判断text字段存在且非空,避免字段缺失、空值导致的报错
    if post.get("text") and target_key in post["text"]:
        listposts.append(post)
print(listposts)

如果需要完全匹配text值等于"abc",把判断条件里的target_key in post["text"]替换为post["text"] == target_key即可。

方案2:全量爬取后再过滤

如果需要同时保留全量爬取数据和筛选结果,可以先存全量数据再用列表推导式筛选:

from facebook_scraper import get_posts

all_posts = []
for post in get_posts("myhealthkkm", pages=1):
    all_posts.append(post)

target_key = "abc"
listposts = [post for post in all_posts if post.get("text") and target_key in post["text"]]
print(listposts)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 20:06:04