课程作业——爬取校园新闻首页的新闻的详情,使用正则表达式,函数抽离

要求:

  1. 用requests库和BeautifulSoup库,爬取校园新闻首页新闻的标题、链接、正文、show-info。
  2. 分析info字符串,获取每篇新闻的发布时间,作者,来源,摄影等信息。
  3. 将字符串格式的发布时间转换成datetime类型
  4. 使用正则表达式取得新闻编号
  5. 生成点击次数的Request URL
  6. 获取点击次数
  7. 将456步骤定义成一个函数 def getClickCount(newsUrl):
  8. 将获取新闻详情的代码定义成一个函数 def getNewDetail(newsUrl):
  9. 尝试用使用正则表达式分析show info字符串,点击次数字符串。

根据上面要求,代码如下:

import requests
from bs4 import BeautifulSoup
from datetime import datetime
import re

# 设置local是处理包含中文格式时间(%Y年%m月%d日)时报错:
# UnicodeEncodeError: 'locale' codec can't encode character 'u5e74'
# import locale
# locale.setlocale(locale.LC_CTYPE, 'chinese')


def crawlOnePageSchoolNews(page_url):
    res = requests.get(page_url)
    res.encoding = 'UTF-8'
    soup = BeautifulSoup(res.text, 'html.parser')
    news = soup.select('.news-list > li')
    for n in news:
        # print(n)
        print('**' * 5 + '列表页信息' + '**' * 10)
        print('新闻链接:' + n.a.attrs['href'])
        print('新闻标题:' + n.select('.news-list-title')[0].text)
        print('新闻描述:' + n.a.select('.news-list-description')[0].text)
        print('新闻时间:' + n.a.select('.news-list-info > span')[0].text)
        print('新闻来源:' + n.a.select('.news-list-info > span')[1].text)
        getNewDetail(n.a.attrs['href'])


def getNewDetail(href):
    print('**' * 5 + '详情页信息' + '**' * 10)
    res1 = requests.get(href)
    res1.encoding = 'UTF-8'
    soup1 = BeautifulSoup(res1.text, 'html.parser')
    news_info = soup1.select('.show-info')[0].text
    info_list = ['来源', '发布时间', '点击', '作者', '审核', '摄影']  # 需要解析的字段
    news_info_set = set(news_info.split('xa0')) - {' ', ''}  # 网页中的 获取后会解析成xa0,所以可以使用xa0作为分隔符
    # 循环打印文章信息
    for n_i in news_info_set:
        for info_flag in info_list:
            if n_i.find(info_flag) != -1:  # 因为时间的冒号采用了英文符所以要进行判断
                if info_flag == '发布时间':
                    # 将发布时间字符串转为datetime格式,方便日后存储到数据库
                    release_time = datetime.strptime(n_i[n_i.index(':') + 1:], '%Y-%m-%d %H:%M:%S ')
                    print(info_flag + ':', release_time)
                elif info_flag == '点击':  # 点击次数是通过文章id访问php后使用js写入,所以这里单独处理
                    getClickCount(href)
                else:
                    print(info_flag + ':' + n_i[n_i.index(':') + 1:])
    news_content = soup1.select('#content')[0].text
    print(news_content)  # 文章内容
    print('————' * 40)


def getClickCount(news_url):
    # http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80
    # 上面链接为文章页得出访问次数的URL
    click_num_url = 'http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80'
    # 通过正则表达式得出文章id
    click_num_url = click_num_url.format(re.search('_(.*)/(.*).html', news_url).group(2))
    res2 = requests.get(click_num_url)
    res2.encoding = 'UTF-8'
    # $('#todaydowns').html('5');$('#weekdowns').html('106');$('#monthdowns').html('129');$('#hits').html('399');
    # 上面为response的内容

    # 使用正则表达式的方法获取点击次数
    # res2.text[res2.text.rindex("('") + 2:res2.text.rindex("')")],不使用正则的方式
    print('点击:' + re.search("$('#hits').html('(d*)')", res2.text).group(1))


crawlOnePageSchoolNews('http://news.gzcc.cn/html/xiaoyuanxinwen/')

以上代码运行结果大致如下:

**********列表页信息********************
新闻链接:http://news.gzcc.cn/html/2018/xiaoyuanxinwen_0401/9167.html
新闻标题:党情国情在我心,理想信仰伴我行——我校举行十九届三中全会和2018年“两会”知识竞赛
新闻描述:3月29日中午,我校马克思主义学院举办十九届三中全会和2018年“两会”知识竞赛,进一步坚定大学生马克思主义信仰。
新闻时间:2018-04-01
新闻来源:马克思主义学院
**********详情页信息********************
作者:陈流芳
点击:196
来源:马克思主义学院
发布时间:2018-04-01 11:57:00 
审核:权麟春

     为了认真贯彻党的.....

————————————————————————————————————————————————————————————————————
**********列表页信息********************
新闻链接:http://news.gzcc.cn/html/2018/xiaoyuanxinwen_0401/9163.html
新闻标题:校党委书记吕泉荣参加结对子班级主题班会
新闻描述:3月29日下午,校党委书记吕泉荣作为结对子班级指导老师,参加会计学院16会计1班“学业成绩分析”主题班会。
新闻时间:2018-04-01
新闻来源:学生工作处
**********详情页信息********************
......

原文地址:https://www.cnblogs.com/lger/p/8707991.html