python实现的rss阅读器实例

本文实例讲述了python实现的rss阅读器。分享给大家供大家参考。具体如下:

# -*- coding:utf-8 -*-
# file: pyrss.py
#
import tkinter
import urllib
import xml.parsers.expat
class myxml: # xml解析类
def __init__(self, edit):
self.parser = xml.parsers.expat.parsercreate() # 生成xmlparser
self.parser.startelementhandler = self.start # 起始标记处理方法
self.parser.endelementhandler = self.end # 结束标记处理方法
self.parser.characterdatahandler = self.data # 字符数据处理方法
self.title = false # 状态标志
self.description = false
self.date = false
self.edit = edit # 多行文本框对象
def start(self, name, attrs): # 起始标记处理方法
if name == ‘title’: # 判断是否为title元素
self.title = true # 标志设为真
elif name == ‘description’:
self.description = true
elif name == ‘pubdate’: # 判断是否为pubdate
self.date = true # 标志设为真
else:
pass
def end(self, name): # 结束标记处理
if name == ‘title’:
self.title = false # 标志设为假
elif name == ‘description’:
self.description = false
elif name == ‘pubdate’:
self.date = false # 标志设为假
else:
pass
def data(self,data): # 字符数据处理方法
if self.title: # 根据标志状态输出数据
self.edit.insert(tkinter.end,
‘******************************\n’)
self.edit.insert(tkinter.end, ‘title: ‘)
self.edit.insert(tkinter.end, data + ‘\n’)
elif self.description:
self.edit.insert(tkinter.end, ‘date: ‘)
self.edit.insert(tkinter.end, data + ‘\n’)
elif self.date:
self.edit.insert(tkinter.end, ‘date: ‘)
self.edit.insert(tkinter.end, data + ‘\n’)
else:
pass
def feed(self, data):
self.parser.parse(data, 0)
class window:
def __init__(self, root):
self.root = root # 创建组件
self.entryurl = tkinter.entry(root,width = 30)
self.entryurl.place(x = 65, y = 15)
self.get = tkinter.button(root,
text = ‘读取rss’, command = self.get, font = (‘system’,’10’))
self.get.place(x = 350, y = 15)
self.frame = tkinter.frame(root, bd=2)
self.scrollbar = tkinter.scrollbar(self.frame)
self.edit = tkinter.text(self.frame,yscrollcommand = self.scrollbar.set,
width = 96, height = 32)
self.scrollbar.config(command=self.edit.yview)
self.edit.pack(side = tkinter.left)
self.scrollbar.pack(side=tkinter.right, fill=tkinter.y)
self.frame.place(y = 50)
def get(self):
url = self.entryurl.get()
page = urllib.urlopen(url) # 打开url
data = page.read() # 读取url内容
parser = myxml(self.edit) # 生成实例对象
parser.feed(data) # 处理xml数据
page.close()
root = tkinter.tk()
root.title(‘rss 阅读器’)
window = window(root)
root.minsize(700,500)
root.maxsize(700,500)
root.mainloop()

希望本文所述对大家的python程序设计有所帮助。

发表评论