使用 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}')
newslib 或直接解析原始訊息格式。