萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python nntplib 讀取新聞組 (NNTP) 完整範例

使用 Python 標準庫 nntplib 連接 NNTP 伺服器,列出新聞組文章、顯示主旨、讀取指定文章內容。

基本流程

from nntplib import NNTP

# 連接公開 NNTP 伺服器
with NNTP('news.aioe.org') as nntp:
    # 選擇新聞組
    resp, count, first, last, name = nntp.group('comp.lang.python')
    print(f'Group: {name}, Articles: {count}, Range: {first}-{last}')
    
    # 取得最後 10 篇主旨
    resp, subjects = nntp.xhdr('subject', f'{first}-{last}')
    for num, subj in subjects[-10:]:
        print(f'{num}: {subj}')
    
    # 互動式選擇閱讀
    try:
        choice = input('Which article to read? (number): ')
        resp, num, msgid, lines = nntp.body(choice)
        for line in lines:
            print(line.decode('utf-8', errors='replace'))
    except (ValueError, KeyboardInterrupt):
        print('Cancelled')

關鍵方法速查

方法說明
group(name)選擇新聞組,回傳 (回應, 文章數, 首篇號, 末篇號, 組名)
xhdr(header, range)取得指定標頭 (subject/from/date) 範圍內的值
head(article)取得文章完整標頭
body(article)取得文章內文 (列表 of bytes)
article(article)取得標頭+內文
post(data)發布文章 (需權限)
quit()關閉連線

編碼處理

NNTP 回傳位元組串流,需依實際編碼解碼 (常見 UTF-8、ISO-8859-1):

for line in lines:
    print(line.decode('utf-8', errors='replace'))

錯誤處理

from nntplib import NNTP, NNTPError

try:
    with NNTP('news.example.com', timeout=10) as nntp:
        nntp.login('user', 'pass')  # 若需認證
        # ...
except NNTPError as e:
    print(f'NNTP 協議錯誤: {e}')
except ConnectionRefusedError:
    print('無法連接伺服器')
except Exception as e:
    print(f'其他錯誤: {e}')

現代替代方案

  • 新聞組已較少見,現代多改用 RSS/Atom、Web API、郵件列表、Discord/Slack 等。
  • 若需處理 Usenet 存檔,可考慮 newslib 或直接解析原始訊息格式。
copyright © 萬盛學電腦網 all rights reserved