基于Python爬虫与Tkinter构建本地新闻聚合小程序
本文介绍如何利用Python的requests库获取HTML页面,结合BeautifulSoup解析标签提取新闻标题与正文,并通过Tkinter构建图形界面展示内容。最后使用PyInstaller将脚本编译为独立的Windows可执行文件,实现无需Python环境的本地新闻查看工具。
核心代码
主要依赖requests库的get方法下载HTML网页,并利用bs4库的BeautifulSoup模块对HTML内容进行结构化分析。
from requests import get
from bs4 import BeautifulSoup as bs
from datetime import datetime as dt
def Today(style=1):
date = dt.today()
if style!=1: return f'{date.month}月{date.day}日'
return f'{date.year}-{date.month:02}-{date.day:02}'
def SinaNews(style=1):
url1 = 'http://news.***.com.cn/'
if style==1: url1 += 'world'
elif style==2: url1 += 'china'
else: url1='https://mil.news.sina.com.cn/'
text = get(url1)
text.encoding='uft-8'
soup = bs(text.text,'html.parser')
aTags = soup.find_all("a")
return [(t.text,t['href']) for t in aTags if Today() in str(t)]
爬取标题
>>> for i,news in enumerate(SinaNews(1)): print(f'No{i+1}:',news[0])
No1: 外媒:***** No2: 日媒:****** ......
.......
内容已马赛克!!! >>>
作为初次尝试爬虫的项目,为了降低难度,选择了一个无需复杂破解即可直接获取内容的新闻网站。该程序以国际、国内和军事新闻三个板块作为数据源,通过requests.get下载网页源码后,利用BeautifulSoup解析HTML文本。由于目标网页中所有带有日期信息的<a href=...>标签恰好对应所需数据,因此可以直接提取。
爬取正文
在获取新闻列表后,根据链接下载具体的正文网页。通过分析HTML结构可知,id为'article'的<div>层级包含了新闻正文内容。使用.get_text()函数提取纯文本,并配合适当的格式处理逻辑(如去除多余空格和换行)来优化显示效果。
>>> def NewsDownload(url):
html = get(url)
html.encoding='uft-8'
soup = bs(html.text,'html.parser')
text = soup.find('div',id='article').get_text().strip()
text = text.replace('点击进入专题:','相关专题:')
text = text.replace(' ','\n ')
while '\n\n\n' in text:
text = text.replace('\n\n\n','\n\n')
return text
>>> url = 'https://******/w/2021-09-29/doc-iktzqtyt8811588.shtml'
>>> NewsDownload(url)
'原标题:******************************************************'
>>>
界面代码
使用Python内置的图形界面库tkinter,选取Text、Listbox、Scrollbar和Button等控件。通过设置基本属性、确定布局位置以及绑定事件命令,经过调试最终完成程序开发。
源代码 News.pyw :其中涉及的网站名称已马赛克!
from requests import get
from bs4 import BeautifulSoup as bs
from datetime import datetime as dt
from os import path
import tkinter as tk
def Today(style=1):
date = dt.today()
if style!=1: return f'{date.month}月{date.day}日'
return f'{date.year}-{date.month:02}-{date.day:02}'
def SinaNews(style=1):
url1 = 'http://news.****.com.cn/'
if style==1: url1 += 'world'
elif style==2: url1 += 'china'
else: url1='https://mil.****.com.cn/'
text = get(url1)
text.encoding='uft-8'
soup = bs(text.text,'html.parser')
aTags = soup.find_all("a")
return [(t.text,t['href']) for t in aTags if Today() in str(t)]
def NewsList(i):
global news
news = SinaNews(i)
tList.delete(0,tk.END)
for idx,item in enumerate(news):
tList.insert(tk.END,f'{idx+1:03} {item[0]}')
tText.config(state=tk.NORMAL)
tText.delete(0.0,tk.END)
tText.config(state=tk.DISABLED)
NewsShow(0)
def NewsList1(): NewsList(1)
def NewsList2(): NewsList(2)
def NewsList3(): NewsList(3)
def NewsShow(idx):
if idx!=0:
idx = tList.curselection()[0]
title,url = news[idx][0],news[idx][1]
html = get(url)
html.encoding='uft-8'
soup = bs(html.text,'html.parser')
text = soup.find('div',id='article').get_text().strip()
text = text.replace('点击进入专题:','相关专题:')
text = text.replace(' ','\n ')
while '\n\n\n' in text:
text = text.replace('\n\n\n','\n\n')
tText.config(state=tk.NORMAL)
tText.delete(0.0,tk.END)
tText.insert(tk.END, title+'\n\n'+text)
tText.config(state=tk.DISABLED)
def InitWindow(self,W,H):
Y = self.winfo_screenheight()
winPosition = str(W)+'x'+str(H)+'+8+'+str(Y-H-100)
self.geometry(winPosition)
icoFile = 'favicon.ico'
f = path.exists(icoFile)
if f: win.iconbitmap(icoFile)
self.resizable(False,False)
self.wm_attributes('-topmost',True)
self.title(bTitle[0])
SetControl()
self.update()
self.mainloop()
def SetControl():
global tList,tText
tScroll = tk.Scrollbar(win, orient=tk.VERTICAL)
tScroll.place(x=450,y=320,height=300)
tList = tk.Listbox(win,selectmode=tk.BROWSE,yscrollcommand=tScroll.set)
tScroll.config(command=tList.yview)
for idx,item in enumerate(news):
tList.insert(tk.END,f'{idx+1:03} {item[0]}')
tList.place(x=15,y=320,width=435,height=300)
tList.select_set(0)
tList.focus()
bW,bH = 70,35 #按钮的宽高
bX,bY = 95,270 #按钮的坐标
tBtn1 = tk.Button(win,text=bTitle[1],command=NewsList1)
tBtn1.place(x=bX,y=bY,width=bW,height=bH)
tBtn2=tk.Button(win,text=bTitle[2],command=NewsList2)
tBtn2.place(x=bX+100,y=bY,width=bW,height=bH)
tBtn3 = tk.Button(win,text=bTitle[3],command=NewsList3)
tBtn3.place(x=bX+200,y=bY,width=bW,height=bH)
tScroll2 = tk.Scrollbar(win, orient=tk.VERTICAL)
tScroll2.place(x=450,y=10,height=240)
tText = tk.Text(win,yscrollcommand=tScroll2.set)
tScroll2.config(command=tText.yview)
tText.place(x=15,y=10,width=435,height=240)
tText.config(state=tk.DISABLED,bg='azure',font=('宋体', '14'))
NewsShow(0)
tList.bind("<Double-Button-1>",NewsShow)
if __name__=='__main__':
win = tk.Tk()
bTitle = ('今日新闻','国际新闻','国内新闻','军事新闻')
news = SinaNews()
InitWindow(win,480,640)
此处提供完整代码,不再进行逐行详细分析。如有具体需求,欢迎留言讨论。该程序在Win7系统配合Python3.8.8环境下测试可无错运行。文中涉及的网站域名已做隐藏处理,如需获取原始链接可私下联系作者。
软件编译
使用pyinstaller.exe工具将Python脚本编译为单个可执行文件。需注意源码文件的后缀名应使用.pyw,否则编译后的程序运行时会弹出黑色的CMD命令行窗口。另外分享一个小技巧:大多数网站的Logo图标文件(favicon.ico)通常位于网站根目录下,路径格式一般为: http(s)://websiteurl.com(.cn)/favicon.ico
编译命令如下:
D:\>pyinstaller --onefile --nowindowed --icon="D:\favicon.ico" News.pyw
编译完成后,在dist文件夹下会生成一个News.exe可执行文件,文件大小约为15M,体积在可接受范围内。
程序打包后即可直接分发使用,如果觉得有用,请记得收藏支持,谢谢!
到此这篇关于结合Python网络爬虫做一个今日新闻小程序的文章就介绍到这了,更多相关Python 新闻程序内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









