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

请求优化Telegram代码:仅抓取带用户名的用户

Telegram群成员抓取代码优化:仅保留含用户名的用户

你的需求很明确,只需要在遍历群成员时跳过没有username的用户即可,同时还要修正原代码里表头和内容列数不匹配的问题(原代码漏写了序号列)。以下是修改后的完整代码:

import csv
import time

print('Fetching Members...')
all_participants = client.iter_participants(target_group, limit=None, filter=None, aggressive=True)

with open("data.csv","w",encoding='UTF-8') as f:
    writer = csv.writer(f,delimiter=",",lineterminator="\n")
    # 表头定义
    writer.writerow(['sr. no.', 'username','user id', 'access hash','first_name','last_name','group', 'group id','status'])
    i = 0
    try:
        for user in all_participants:
            # 核心判断:没有username直接跳过当前用户
            if not user.username:
                continue
                
            i += 1
            # 简化空值处理(可选,主要处理姓名字段)
            username = user.username
            first_name = user.first_name or ""
            last_name = user.last_name or ""
            
            # 写入CSV:补上序号i,和表头对应
            writer.writerow([
                i, 
                username, 
                user.id, 
                user.access_hash, 
                first_name, 
                last_name, 
                target_group.title, 
                target_group.id, 
                user.status
            ])
            time.sleep(0.1)
    except Exception as e:
        print(f"抓取过程出错: {e}")

关键修改说明:

  • 过滤无用户名用户:添加if not user.username: continue,一旦检测到用户没有username,直接跳过后续处理,不写入CSV。
  • 修正列数不匹配:原代码写入时遗漏了表头里的sr. no.(序号),现在补上i,保证表头和内容一一对应,避免CSV格式混乱。
  • 简化空值处理:用or ""替代原有的if-else判断,让代码更简洁,同时保证空值时写入空字符串。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 07:43:10