目录

核心代码

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下载网页后,分析所得html文本,所有<a href=…>标记带日期刚好所需要的。

爬取正文

然后再根据url下载正文网页,分析可知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)
'原标题:******************************************************'
>>> 

界面代码

使用内置的图形界面库 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编译成单个运行文件,注意源码文件的后缀名应该用.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还能接受。 

反正拿走就能直接用

以上就是python小程序爬取今日新闻拿走就能用的详细内容,更多关于python小程序的资料请关注www.887551.com其它相关文章!