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

如何用Selenium从Telegram网页版Z中提取Chat-ID(无需打开聊天)

提取Telegram网页版Z的Chat-ID(无需打开聊天)

针对你无法打开聊天但需要提取Chat-ID的需求,结合你提到的data-peer-id属性和现有Selenium代码,提供以下三种可行方案:


方案1:直接定位DOM中的data-peer-id属性

Telegram网页版Z的侧边栏聊天项仍可能携带data-peer-id属性,只是DOM结构与K版不同,可通过通用属性选择器直接抓取:

from seleniumwire import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.firefox import GeckoDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import sys

URL = 'https://web.telegram.org/'
firefox_options = webdriver.FirefoxOptions()
path_to_firefox_profile = "output_files\\firefox\\ghr2wgpa.default-release"
profile = webdriver.FirefoxProfile(path_to_firefox_profile)
profile.set_preference("dom.webdriver.enabled", False)
profile.set_preference('useAutomationExtension', False)
firefox_options.set_preference("general.useragent.override", 'user-agent=Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0')
profile.set_preference("security.mixed_content.block_active_content", False)
profile.update_preferences()
firefox_options.add_argument("--width=1400")
firefox_options.add_argument("--height=1000")
driver_installation = GeckoDriverManager().install()
service = Service(driver_installation)
if sys.platform == 'win32':
    from subprocess import CREATE_NO_WINDOW
    service.creationflags = CREATE_NO_WINDOW

# 注意:原代码中capabilities=caps未定义,此处删除该参数避免报错
driver = webdriver.Firefox(options=firefox_options, firefox_profile=profile, service=service)
driver.get(URL)

# 等待侧边栏加载完成,抓取所有带data-peer-id的元素
wait = WebDriverWait(driver, 15)
chat_elements = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, '[data-peer-id]')))

# 提取并输出Chat-ID和对应聊天名称
for elem in chat_elements:
    chat_id = elem.get_attribute('data-peer-id')
    chat_name = elem.text.strip().split('\n')[0]  # 只取第一行名称
    print(f"聊天名称: {chat_name}, Chat-ID: {chat_id}")

driver.close()
driver.quit()

如果通用选择器无效,可在浏览器开发者工具中查看聊天项的父容器类名,修改CSS选择器为更具体的规则,比如:div.chat-item-container[data-peer-id]。


方案2:通过SeleniumWire监听网络请求获取

利用seleniumwire的网络监听功能,抓取Telegram获取聊天列表的API请求,直接从响应中提取Chat-ID:

# 基础代码同方案1,仅在driver.get(URL)后添加以下逻辑
import time
import json

driver.get(URL)
time.sleep(8)  # 等待页面加载和API请求完成

# 遍历所有请求,找到聊天列表接口
for request in driver.requests:
    if '/api/getDialogs' in request.url and request.response:
        # 解析API响应JSON
        response_json = json.loads(request.response.body.decode('utf-8'))
        dialogs = response_json.get('result', {}).get('dialogs', [])
        # 提取每个对话的Chat-ID
        for dialog in dialogs:
            peer_info = dialog.get('peer', {})
            chat_id = peer_info.get('id')
            chat_type = peer_info.get('_')  # 区分用户/群聊/频道
            print(f"Chat-ID: {chat_id}, 类型: {chat_type}")
        break  # 找到目标请求后停止遍历

注:Telegram网页版Z的API路径可能为/api/v1/getDialogs,可在浏览器Network标签中确认实际路径后调整判断条件。


方案3:注入JS脚本提取数据

通过Selenium执行原生JS,直接调用页面逻辑或抓取DOM数据,适配Z版的页面结构:

# 基础代码同方案1,在driver.get(URL)后添加以下逻辑
wait = WebDriverWait(driver, 15)
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '[data-peer-id]')))

# 执行JS脚本提取所有聊天的ID和名称
chat_list = driver.execute_script("""
    const result = [];
    document.querySelectorAll('[data-peer-id]').forEach(item => {
        result.push({
            id: item.getAttribute('data-peer-id'),
            name: item.textContent.trim().split('\\n')[0]
        });
    });
    return result;
""")

# 打印结果
for chat in chat_list:
    print(f"聊天名称: {chat['name']}, Chat-ID: {chat['id']}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 15:35:51