资讯专栏INFORMATION COLUMN

Python “今日新闻”一个小程序,拿走就能用!

nanfeiyan / 2743人阅读

核心代码

requests.get 下载html网页
bs4.BeautifulSoup 分析html内容

from requests import getfrom bs4 import BeautifulSoup as bsfrom datetime import datetime as dtdef 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下载网页后,分析所得html文本,所有标记带日期刚好所需要的。

爬取正文

然后再根据url下载正文网页,分析可知id=‘article’的

层就是正文所在位置,.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)"原标题:******************************************************">>> 

界面代码

使用内置的图形界面库 tkinter 控件 Text 、Listbox、Scrollbar、Button。设置基本属性、放置位置、绑定命令,然后调试到程序完工!

源代码 News.pyw :其中涉及的网站名称已马赛克!

from requests import getfrom bs4 import BeautifulSoup as bsfrom datetime import datetime as dtfrom os import pathimport tkinter as tkdef 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("",NewsShow)if __name__=="__main__":    win = tk.Tk()    bTitle = ("今日新闻","国际新闻","国内新闻","军事新闻")    news = SinaNews()    InitWindow(win,480,640)

奉上全部代码,在此就不作详细分析了,如有需要请留言讨论。我的使用环境 Win7+Python3.8.8 下可以无错运行!文中涉及网站名称已打上马赛克,猜不出名字的可以私下里问我。

软件编译

使用pyinstaller.exe编译成单个运行文件,注意源码文件的后缀名应该用.pyw否则会有cmd黑窗口出现。还有一个小知识点,任意网站的Logo图标icon文件,一般都能在根目录里下载到,即:
http(s)://websiteurl.com(.cn)/favicon.ico

编译命令如下:

D:/>pyinstaller --onefile --nowindowed --icon="D:/favicon.ico" News.pyw

编译完成后,在dist文件夹下生成一个News.exe可执行文件,大小约15M还能接受。 

反正拿走就能直接用,临走前给个一键三连吧,谢谢!

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/121684.html

相关文章

  • 年薪30万的软件测试工程师需要具备的实力有哪些?

    摘要:的分类的六要素的生命周期。第二阶段测试工具自学时会用即可,不必精通需求分析工具用例编写相关函数统计数据整合条件判定数据有效性等性能测试工具。语言数据库都是必须的,当然测试工具也是要会的。  软实力  ● 关于刚入职时 ● 关于对待问题 ● 关于执行力 ● 关于个性 ● 关于下...

    骞讳护 评论0 收藏0
  • Python所有方向的学习路线,你们要的知识体系在这,千万别做了无用功!

    摘要:适用人群爬虫方向数据分析方向非程序员加薪四开发前后端开发是程序员职业中的热门,目前来讲,人才缺口依然很大。寄语上面就是所有方向的学习路线了,把你感兴趣的方向掌握了之后,你去找工作不是什么问题的。 ...

    opengps 评论0 收藏0
  • App 端自动化的最佳方案,完全解放双手!

    摘要:前言大家好,我是安果之前写过一篇文章,文中提出了一种方案,可以实现每天自动给微信群群发新闻早报如何利用爬虫实现给微信群发新闻早报详细但是对于很多人来说,首先编写一款需要一定的移动端开发经验,其次还需要另外编写无障碍服务应用,如此显得有一定难1. 前言大家好,我是安果!之前写过一篇文章,文中提出了一种方案,可以实现每天自动给微信群群发新闻早报如何利用 Python 爬虫实现给微信群发新闻早报?...

    番茄西红柿 评论0 收藏2637
  • python里能不能用中文

    摘要:而且我们一直在讲的,也可以用中文来编程。带来的一个额外功能就是,你可以使用中文作为变量名。另外如果在代码里写中文,别忘了在开头加上或的声明。 现代计算机和编程的起源和推动力量主要源自美国,再加上26个字母很便于表示(算上大小写,6位bit就够了),因此英语一直是编程领域的不二之选。但这就给部分非英语国家的编程学习者带来一些困扰。以至于有些人还没开始学,就担心自己的英语问题。这完全没必要...

    anquan 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<