Python笔记 之 nntp模块

nntp模块定义实现网络新闻传输协议客户端的NNTP类,可以用于在互联网上阅读Usenet新闻组及向其发布文章。
nntp官方说明文档
注意:本人未能找到国内相关网站的NNTP服务器地址,所测试服务器均为官方例子中的NNTP服务器地址。
使用nntp模块阅读网络新闻

官方小例子

示例1

浏览news.gmane.io 网站 gmane.comp.python.committers 新闻组前5条新闻的主题

import nntplib

def example1(site = 'news.gmane.io',group='gmane.comp.python.committers'):
    s = nntplib.NNTP(site)
    (resp, count, first, last, name) = s.group(group)
    print('Rest:', resp, '\n',
          'Count:', count, '\n',
          'First:', first, '\n',
          'Last:', last, '\n',
          'Name:', name, '\n')
    (resp,overviews) = s.over((first,first+4))
    print('Resp:', resp, '\n',
          'Overviews:', overviews)
    for id, view in overviews:
        print(id, nntplib.decode_header(view['subject']))

结果

Rest: 211 7150 1 7151 gmane.comp.python.committers 
 Count: 7150 
 First: 1 
 Last: 7151 
 Name: gmane.comp.python.committers 

Resp: 224 Overview information for 1-5 follows 
 Overviews: [(1, {'subject': 'Nominate Hirokazu Yamamoto (oceancity) for commit privs.', 'from': 'Trent Nelson <tnelson@onresolve.com>', 'date': 'Mon, 11 Aug 2008 20:27:36 +0100', 'message-id': '<6167796BFEB5D0438720AC212E89A6B0078F4D64@exchange.onresolve.com>', 'references': '', ':bytes': '3910', ':lines': '5', 'xref': 'news.gmane.org gmane.comp.python.committers:1'}), (2, {'subject': 'Re: Nominate Hirokazu Yamamoto (oceancity) for commit privs.', 'from': '"Jesse Noller" <jnoller@gmail.com>', 'date': 'Mon, 11 Aug 2008 15:38:05 -0400', 'message-id': '<4222a8490808111238p49c57e6buc806b1f725812520@mail.gmail.com>', 'references': '<6167796BFEB5D0438720AC212E89A6B0078F4D64@exchange.onresolve.com>', ':bytes': '5404', ':lines': '14', 'xref': 'news.gmane.org gmane.comp.python.committers:2'}), (3, {'subject': 'Re: Nominate Hirokazu Yamamoto (oceancity) for commit privs.', 'from': '=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?= <martin@v.loewis.de>', 'date': 'Mon, 11 Aug 2008 21:56:13 +0200', 'message-id': '<48A0995D.6010902@v.loewis.de>', 'references': '<6167796BFEB5D0438720AC212E89A6B0078F4D64@exchange.onresolve.com>', ':bytes': '4304', ':lines': '17', 'xref': 'news.gmane.org gmane.comp.python.committers:3'}), (4, {'subject': 'Re: Nominate Hirokazu Yamamoto (oceancity) for commit privs.', 'from': 'Christian Heimes <lists@cheimes.de>', 'date': 'Mon, 11 Aug 2008 21:42:47 +0200', 'message-id': '<48A09637.2090102@cheimes.de>', 'references': '<6167796BFEB5D0438720AC212E89A6B0078F4D64@exchange.onresolve.com>', ':bytes': '4271', ':lines': '11', 'xref': 'news.gmane.org gmane.comp.python.committers:4'}), (5, {'subject': 'Re: Nominate Hirokazu Yamamoto (oceancity) for commit privs.', 'from': 'Jeroen Ruigrok van der Werven <asmodai@in-nomine.org>', 'date': 'Mon, 11 Aug 2008 22:15:34 +0200', 'message-id': '<20080811201534.GL57679@nexus.in-nomine.org>', 'references': '<6167796BFEB5D0438720AC212E89A6B0078F4D64@exchange.onresolve.com> <48A0995D.6010902@v.loewis.de>', ':bytes': '5100', ':lines': '14', 'xref': 'news.gmane.org gmane.comp.python.committers:5'})]
1 Nominate Hirokazu Yamamoto (oceancity) for commit privs.
2 Re: Nominate Hirokazu Yamamoto (oceancity) for commit privs.
3 Re: Nominate Hirokazu Yamamoto (oceancity) for commit privs.
4 Re: Nominate Hirokazu Yamamoto (oceancity) for commit privs.
5 Re: Nominate Hirokazu Yamamoto (oceancity) for commit privs.
示例2

上传本地 article.txt 文件 到 news.gmane.io 网站

import nntplib

def example2(site = 'news.gmane.io'):
    s = nntplib.NNTP(site)
    f = open('article.txt','rb')
    print(s.post(f))
    s.quit()

简要介绍

建立连接

#nntplib.NNTP(host, port=119, user=None, password=None, readermode=None, usenetrc=False[, timeout])
使用NNTP协议创建与host的连接,并开始监听port端口
host是一个有效的nntp服务器
usenetrc标识为True时需要提供user,password向服务器请求验证

NNTP服务器属性

#NNTP.nntp_version
返回NNTP协议的版别号,返回值为 int 型
#NNTP.nntp_implementation
返回NNTP服务器的软件名称和版本的字符串,返回值为 string 型。

断开连接

#NNTP.quit()
断开与NNTP服务器的链接

获取服务器欢迎语

#NNTP.getwelcome()

获取服务器功能列表

#NNTP.getcapabilities()
返回服务器公布的功能名称的dict实例。在不理解CAPABILITIES命令的旧服务器上,将返回一个空字典。

登录认证

#NNTP.login(user=None, password=None, usenetrc=True)
使用用户名和密码登录

启动加密传输

#NNTP.starttls(context=None)
在NNTP连接上启用加密

返回新闻组列表

#NNTP.newgroups(date, *, file=None)
返回从date开始新建的新闻组列表

返回新闻列表

#NNTP.newnews(group, date, *, file=None)
返回新闻组group,从时间date开始的新闻
如果group为 * 则返回所有新闻组新闻
NNTP服务器管理员经常禁用此命令

返回服务器新列表

#NNTP.list(group_pattern=None, *, file=None)
返回NNTP服务器的分组列表

返回新闻组的描述信息

#NNTP.descriptions(grouppattern)
#NNTP.description(group)

选择指定新闻组

#NNTP.group(name)
选择指定新闻组为当前新闻组

浏览指定新闻

#NNTP.over(message_spec, *, file=None)
浏览指定范围的新闻,message_spec为一个元祖区间

获取帮助信息

#NNTP.help(*, file=None)

获取消息状态

#NNTP.stat(message_spec=None)
获取指定消息状态
#NNTP.next()
下一条状态
#NNTP.last()
上一条状态

获取文章

#NNTP.article(message_spec=None, *, file=None)
获取文章

获取文章头

#NNTP.head(message_spec=None, *, file=None)
获取文章头

获取文章内容

#NNTP.body(message_spec=None, *, file=None)
获取文章内容

上传文章

#NNTP.post(data)
上传文章,文章必须以字节形式上传
#NNTP.ihave(message_id, data)

获取服务器时间

#NNTP.date()

设置调试级别

#NNTP.set_debuglevel(level)
默认0,不输出调试信息
1,每行一条调试信息
2,详细的调试信息

读取文章内容

#NNTP.xhdr(hdr, str, *, file=None)
hdr参数是标题关键字,如“subject”。
str参数的格式应为first-last,其中first和last是要搜索的第一个和最后一个文章编号。
返回一个元祖(response,list),其中list是一个列表(id,text),其中id是一个文章编号,text是该文章的标题的文本。

测试代码

import nntplib,datetime

def getNews(site = 'news.gmane.io',group='gmane.comp.python.committers'):
    server = nntplib.NNTP(site)
    print('Version:',server.nntp_version)
    print('Implementation:',server.nntp_implementation)
    print('Welcome:',server.getwelcome())
    print('Capabilities:',server.getcapabilities())
    print('Newgroups:',server.newgroups(datetime.date.today()-datetime.timedelta(days=30)))
    #print('Newnews:', server.newnews('*',datetime.date.today() - datetime.timedelta(days=30)))
    '''
    (response, list) = server.list()
    print('Response:',response,'\n',
          'List:',list)'''
    print(server.descriptions(group))
    print(server.description(group))
    print(server.help())
    #print(server.slave())
    (resp,count,first,last,name) = server.group(group)
    print('First:', server.stat(first))
    print('Next:',server.next())
    print('Last:',server.last())
    print('Article:',server.article(first))
    print('Date:',server.date())
    print('Rest:',resp,'\n',
          'Count:',count,'\n',
          'First:',first,'\n',
          'Last:',last,'\n',
          'Name:',name,'\n')
    (resp,overviews) = server.over((first,first+9))
    print('Resp:',resp,'\n',
          'Overviews:',overviews)
    for id,view in overviews:
        print(id,nntplib.decode_header(view['subject']))
    (resp,subs) = server.xhdr('subject',(str(first)+'-'+str(last)))
    print('Rest:',resp,'\n',
          'Subs:',subs,'\n')
    for subject in subs[-10:]:
        print(subject)
    number = input('Which article do you want to read?')
    (id,list) = server.body(str(number))
    print(
          'Id:',id,'\n',
          'List:',list)
    for line in list:
        print(line)
    server.quit()
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值