数据结构化与保存

1. 将新闻的正文内容保存到文本文件。

2. 将新闻数据结构化为字典的列表:

  • 单条新闻的详情-->字典news
  • 一个列表页所有单条新闻汇总-->列表newsls.append(news)
  • 所有列表页的所有新闻汇总列表newstotal.extend(newsls)

3. 安装pandas,用pandas.DataFrame(newstotal),创建一个DataFrame对象df.

4. 通过df将提取的数据保存到csv或excel 文件。

 

import requests, re, pandas, openpyxl
from bs4 import BeautifulSoup
from datetime import datetime


# 获取新闻点击次数
def getnewsclick(url):
    newsId = re.search(r'\_\d{4}\/(.*).html', url).group(1)
    clickUrl = 'http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80'.format(newsId)
    clickRes = requests.get(clickUrl)
    # 利用正则表达式获取新闻点击次数
    clickCount = int(re.search("hits'\).html\('(.*)'\);", clickRes.text).group(1))
    return clickCount


# 获取新闻细节
def getnewsdetail(newsurl):
    resd = requests.get(newsurl)
    resd.encoding = 'utf-8'
    soupd = BeautifulSoup(resd.text, 'html.parser')
    newsDict = {}
    content = soupd.select('#content')[0].text
    info = soupd.select('.show-info')[0].text
    newsDict['title'] = soupd.select('.show-title')[0].text
    date = re.search('(\d{4}.\d{2}.\d{2}\s\d{2}.\d{2}.\d{2})', info).group(1)  # 识别时间格式
    # 识别一个至三个数据
    if info.find('作者') > 0:
        newsDict['author'] = re.search('作者:((.{2,4}\s|.{2,4}、){1,3})', info).group(1)
    else:
        newsDict['author'] = 'none'
    if info.find('审核') > 0:
        newsDict['check'] = re.search('审核:((.{2,4}\s){1,3})', info).group(1)
    else:
        newsDict['check'] = 'none'
    if info.find('来源') > 0:
        first = re.search('来源:(.*)\s*点', info).group(1)
        if first.find('摄影') > 0:
            newsDict['sources'] = re.search('(.*)\s*摄', first).group(1)  # 解决新闻有摄影无法匹配正则的问题
        else:
            newsDict['sources'] = first
    else:
        newsDict['sources'] = 'none'
    if info.find('摄影') > 0:
        newsDict['photo'] = re.search('摄影:(.*)\s*点', info).group(1)
    else:
        newsDict['photo'] = 'none'
    newsDict['dateTime'] = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')  # 用datetime将时间字符串转换为datetime类型
    newsDict['click'] = getnewsclick(newsurl)  # 调用getnewsclick()获取点击次数
    newsDict['content'] = content
    return newsDict


def getlistpage(listurl):  # 获取一页的新闻,转换成列表返回
    res = requests.get(listurl)
    res.encoding = 'utf-8'
    listsoup = BeautifulSoup(res.text, 'html.parser')
    pagelist = []
    for new in listsoup.select('.news-list')[0].select('li'):
        newsUrl = new.select('a')[0]['href']
        pagedict = getnewsdetail(newsUrl)  # 调用getnewsdetail()获取新闻详情
        pagelist.append(pagedict)
        # break
    return pagelist


def gettotalpage(listurl):  # 获取总新闻页面
    res = requests.get(listurl)
    res.encoding = 'utf-8'
    soup = BeautifulSoup(res.text, 'html.parser')
    return int(soup.select('.a1')[0].text.rstrip('')) // 10 + 1


total = []
listUrl = 'http://news.gzcc.cn/html/xiaoyuanxinwen/'
pagelist = getlistpage(listUrl)
total.extend(pagelist)
listCount = gettotalpage(listUrl)
pan = pandas.DataFrame(total)
pan.to_excel('result.xlsx')  # 导出为Excel表格
pan.to_csv('result.csv')  # 导出为csv文件
for i in range(2,listCount):
    listUrl= 'http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html'.format(i)
    total = getlistpage(listUrl)

 

5. 用pandas提供的函数和方法进行数据分析:

  • 提取包含点击次数、标题、来源的前6行数据
  • print(pan[['click', 'sources', 'title']].head(6))
  • 提取‘学校综合办’发布的,‘点击次数’超过3000的新闻。
  • print(pan[(pan['click'] > 3000) & (pan['sources'] == '学校综合办')])
  • 提取'国际学院'和'学生工作处'发布的新闻。
  • selectlist = ['国际学院', '学生工作处']
    print(pan[pan['sources'].isin(selectlist)])
posted @ 2018-04-12 20:59  loadingwhat  阅读(141)  评论(0编辑  收藏  举报