DEV Community

Bachir Djoukbala
Bachir Djoukbala

Posted on

How to scrape a public Telegram channel's posts with Python (no API key, no login)

Public Telegram channels have a web preview at https://t.me/s/<channel>. It needs no login, no bot token and no Telegram API ID. It is plain HTML, and older pages load with a ?before=<post id> parameter. Here is a small script that pulls posts, dates and view counts.

import httpx, re
from bs4 import BeautifulSoup

def scrape(channel, pages=2):
    url = f"https://t.me/s/{channel}"
    posts, before = [], None
    for _ in range(pages):
        r = httpx.get(url, params={"before": before} if before else None, timeout=20, follow_redirects=True)
        r.raise_for_status()
        soup = BeautifulSoup(r.text, "html.parser")
        msgs = soup.select(".tgme_widget_message")
        if not msgs: break
        for m in msgs:
            text = m.select_one(".tgme_widget_message_text")
            t = m.select_one("a.tgme_widget_message_date time")
            v = m.select_one(".tgme_widget_message_views")
            posts.append({"id": m["data-post"],
                          "date": t.get("datetime") if t else None,
                          "views": v.get_text(strip=True) if v else None,
                          "text": text.get_text(" ", strip=True) if text else ""})
        before = msgs[0]["data-post"].split("/")[1]
    return posts
Enter fullscreen mode Exit fullscreen mode

Usage:

posts = scrape("telegram", pages=3)
print(len(posts), posts[0])
Enter fullscreen mode Exit fullscreen mode

Notes from running this:

  • Only public channels with the preview enabled work. Private groups and channels that disable the preview return nothing.
  • ?before=<id> pages backwards, roughly 20 posts per page. Add a short delay between pages and stop on a 429.
  • Views come back as strings such as 1.79M; convert them if you need numbers.
  • This is a preview of public content. Respect the channel owners and Telegram's terms, and do not collect private data.

If you would rather not maintain this, I built the same thing as an Apify actor (disclosure: I am the author). It handles paging, retries, hashtags, mentions and channel info (subscribers, description), and you pay per result: https://apify.com/rejoicing_shanty/telegram-public-channel-scraper

The code above is free to use either way.

Top comments (0)