[新手]使用python爬取光明日报

第一篇爬虫文章

Hello CSDN!
我是一名python新手,前些天自己写了个爬取光明日报的爬虫练习,现在在博客中分享出来。

需要用到的库

  1. requests库
    如果你的电脑上没有这个库,可以通过在命令行中输入 pip install requests 安装。

  2. BeautifulSoup库
    “美味的汤”!
    我们通过BeautifulSoup这个强大的库来解析数据和提取数据。
    如果你的电脑上没有这个库,可以通过在命令行中输入 pip install beautifulsoup4 安装。

  3. fake_useragent库
    我们通过使用这个库来伪造useragent。
    如果你的电脑上没有这个库,可以通过在命令行中输入 pip install fake_useragent 安装。

思路分析

爬取新闻网站上的新闻?听起来是个很困难的事情。
我们尝试一下将这个大问题拆分成小问题,再逐步解决小问题,然后将小问题的结果组合起来。

先把这堆库一股脑丢进去。

import requests
import time
from bs4 import BeautifulSoup
import fake_useragent
ua = fake_useragent.UserAgent()

我们要将爬取到的新闻存储下来,那么就要用到文件读写。

def write_news(a,word):#调用此函数可以完成文件写入
    with open(a,mode='a',encoding='utf-8') as file:
            file.write(word)
            file.write('\n')

一般新闻的标题都是用h1标签存储,正文内容则用p标签存储。
我们用开发者工具检查其网页结构,结果确实如此。

OK,那我们就调用BeautifulSoup库里的方法吧。细节在此不做赘述了。
直接show my code.

def get_guangming_news(url,a): #调用此函数获取新闻正文
    headers={'User-Agent':str(ua.random)}
    res=requests.get(url,headers=headers)
    res.encoding='utf-8'
    soup=BeautifulSoup(res.text,'html.parser')
    h1=soup.find('h1')#找到标签h1
    h1_content=h1.text
    write_news(a,h1_content)
    items=soup.find_all('div',class_='u-mainText')
    for item in items:
        items=item.find_all('p')
    for i in items:
        word=i.text
        write_news(a,word)

至此,我们完成了对某一篇文章的爬取。

那么,如果我想爬取这一天的所有新闻该怎么办呢?

爬取一天的全部新闻

为了爬取这一天的全部新闻,我们首先需要对目标网站的网页结构进行分析。
在这里插入图片描述
我们观察网页发现,每个新闻模块的网页url是固定的,同时日期最新的新闻会被排在最前面。

每一篇文章的标题都被放在一个a标签中,其中href存储的是这篇文章的超链接。
在这里插入图片描述
我们再来编写一个collect_urls函数来收集某天的所有url.

这个日期干脆让用户在程序入口手动输入吧,因为本人比较懒()。

#date=input('请输入要爬取的日期 例如2021-01-31')
def collect_urls(url,date): #调用此函数收集网址并以列表形式返回
    urls=[]
    headers={'User-Agent':str(ua.random)}
    test=requests.get(url,headers=headers)
    test_soup=BeautifulSoup(test.text,'html.parser')
    url=test_soup.find_all('ul',class_='channel-newsGroup')
    for urls_ in url:
        x=urls_.find_all('a')
        for url_s in x :
            i=url_s['href']
            new_date=date[0:7]+'/'+date[-2:]
            if new_date in i:
                urls.append(i)
    return urls

等一下…我们仔细观察一下…好像有相对路径混入绝对路径里了,这可不行。

没办法,只能在主程序开始前加个对url的判断了。

def star_process(a,j,date,weblink):#调用此函数判断<a>标签中是否缺少内容
    print(a+'ok')                  #如果不完整则补全 最终调用函数爬取所有网址
    b=collect_urls(j,date)
    c=len(b)
    newlists=[]
    k=0
    while k < c:
        if 'https' not in b[k]:
            newlist=weblink+b[k]
            newlists.append(newlist)
            k=k+1
        else:
            newlists.append(b[k])
            k=k+1
            continue
    for m in newlists:
        get_guangming_news(m,a)

接下来是程序入口了。

又臭又长警告()

#程序入口
date=input('请输入要爬取的日期 例如2021-01-31')
print('程序开始运行,请不要关闭窗口,耐心等待')
url=[   'https://news.gmw.cn/node_23548.htm',
        'https://news.gmw.cn/node_23547.htm',
        'https://news.gmw.cn/node_23545.htm',
        'https://news.gmw.cn/node_23708.htm',
        'https://politics.gmw.cn/node_9844.htm',
        'https://politics.gmw.cn/node_9840.htm',
        'https://politics.gmw.cn/node_9831.htm',
        'https://politics.gmw.cn/node_9828.htm',
        'https://world.gmw.cn/node_4661.htm',
        'https://world.gmw.cn/node_24177.htm',
        'https://world.gmw.cn/node_4696.htm',
        'https://mil.gmw.cn/node_8986.htm',
        'https://mil.gmw.cn/node_8981.htm',
        'https://mil.gmw.cn/node_8984.htm',
        'https://mil.gmw.cn/node_8982.htm',
        'https://mil.gmw.cn/node_11177.htm'
    ]
for j in url:
    if '23548' in j:
        a='新闻中心时政'+date
        weblink='https://news.gmw.cn/'
        star_process(a,j,date,weblink)
    elif '23547' in j:
        a='新闻中心国际军事'+date
        weblink='https://news.gmw.cn/'
        star_process(a,j,date,weblink)
    elif '23545' in j:
        a='新闻中心经济'+date
        weblink='https://news.gmw.cn/'
        star_process(a,j,date,weblink)
    elif '23708' in j:
        a='新闻中心法治社会'+date
        weblink='https://news.gmw.cn/'
        star_process(a,j,date,weblink)
    if '9844' in j:
        a='时政频道要闻'+date
        weblink='https://politics.gmw.cn/'
        star_process(a,j,date,weblink)
    if '9840' in j:
        a='时政频道国内'+date
        weblink='https://politics.gmw.cn/'
        star_process(a,j,date,weblink)
    if '9831' in j:
        a='时政频道权威发布'+date
        weblink='https://politics.gmw.cn/'
        star_process(a,j,date,weblink)
    elif '9828' in j:
        a='时政频道政策解读'+date
        weblink='https://politics.gmw.cn/'
        star_process(a,j,date,weblink)
    elif '4661' in j:
        a='国际频道国际要闻'+date
        weblink='https://world.gmw.cn/'
        star_process(a,j,date,weblink)
    elif '24177' in j:
        a='国际频道光明推荐'+date
        weblink='https://world.gmw.cn/'
        star_process(a,j,date,weblink)
    elif '4696' in j:
        a='国际频道外媒聚焦'+date
        weblink='https://world.gmw.cn/'
        star_process(a,j,date,weblink)
    elif '8986' in j:
        a='军事频道要闻速揽'+date
        weblink='https://mil.gmw.cn/'
        star_process(a,j,date,weblink)
    elif '8981' in j:
        a='军事频道军事视点'+date
        weblink='https://mil.gmw.cn/'
        star_process(a,j,date,weblink)
    elif '8984' in j:
        a='军事频道中国军情'+date
        weblink='https://mil.gmw.cn/'
        star_process(a,j,date,weblink)
    elif '8982' in j:
        a='军事频道国际军情'+date
        weblink='https://mil.gmw.cn/'
        star_process(a,j,date,weblink)
    elif '11177' in j:
        a='军事频道邻邦扫描'+date
        weblink='https://mil.gmw.cn/'
        star_process(a,j,date,weblink)
print('爬取结束,感谢使用')

因为注意到每个模块的网页url中的数字不同,所以利用了这一特性(笑)。

用了一大串if和elif,我都感觉自己写的太烂了(逃)。

总之,好歹是能爬取了。

后记

之前本想写的惊天地泣鬼神一点,结果写完了发现是这个鸟样,对别人完全没帮助,既没介绍清楚BeautifulSoup库的一些细节,又因为自己懒,也没介绍清楚开发者工具和HTML的标签,只能沦为自娱自乐的一篇文章了。

代码写的烂,文章写的更烂。没脸见人了(ଲ),欢迎各位来鞭尸(ଲ)

  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值