zoukankan      html  css  js  c++  java
  • 数据结构化与保存

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

    def write(filename, content):
        f = open(filename, 'a', encoding='utf-8')
        f.write(content)
        f.close()

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

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

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

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

    import requests
    import pandas
    import openpyxl
    from bs4 import BeautifulSoup
    from datetime import datetime
    import re
    
    #获得新闻点击次数
    def getclick(link):
        newId = re.search('\_(.*).html', link).group(1).split('/')[1]
        click = requests.get('http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80'.format(newId))
        return click.text.split('.html')[-1].lstrip("('").rstrip("');")
    
    
    def getnewsdetail(link):
            resd = requests.get(link)
            resd.encoding = 'utf-8'
            soupd = BeautifulSoup(resd.text, 'html.parser')
    
            content=soupd.select('.show-content')[0].text
            info=soupd.select('.show-info')[0].text
            time=re.search('(d{4}.d{2}.d{2}sd{2}.d{2}.d{2})',info).group(1)
            newsdict={}
            newsdict['title']=soup.select('.show-title')[0].text
            if info.find('作者') > 0:
                newsdict['author'] = re.search('作者:((.{2,4}s|.{2,4}、|.{2,4},|w*s){1,5})', info).group(1)
            else:
                newsdict['author'] = 'none'
            if info.find('审核') > 0:
                newsdict['auditing'] = re.search('审核:((.{2,4}s|.{2,4}、|.{2,4},|w*s){1,5})', info).group(1)
            else:
                newsdict['auditing'] = 'none'
            if info.find('来源:') > 0:
                newsdict['source'] = re.search('来源:(.*)s*摄|点', info).group(1)
            else:
                newsdict['source'] = 'none'
            newsdict['datetime']=datetime.strptime(time,'%Y-%m-%d %H:%M:%S')
            newsdict['click']=getclick(link)
            newsdict['content']=content
            return newsdict
    
    
    
    def getlistpage(listlink):
        res=requests.get(listlink)
        res.encoding='utf-8'
        soup=BeautifulSoup(res.text,'html.parser')
        pagelist=[]
        for news in soup.select('.new-list')[0].select('li'):
            link = news.a.attrs['href']
            pagedict = getnewsdetail(link)
            pagelist.append(pagedict)
        return pagelist
    
    def getnewstotal(link):
        res=requests.get(link)
        res.encoding='utf-8'
        soup=BeautifulSoup(res.text,'html.parser')
        return int(soup.select('.al')[0].text.rstrip(''))//10+1
    
    listlink='http://news.gzcc.cn/html/xiaoyuanxinwen/'
    Allfind=[]
    pagelist=getlistpage(listlink)
    Allfind.extend(pagelist)
    listCount=getnewstotal(listlink)
    pan = pandas.DataFrame(Allfind)
    pan.to_excel('result.xlsx')
    pan.to_csv('result.csv')
    for i in range(2,listCount):
        listlink='http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html'.format(i)
        Allfind=getlistpage(listlink)

    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)])
  • 相关阅读:
    面试题:垂直居中几种方法
    零碎记忆--随机
    v-model 和 :model 的区别
    Vue--keep-alive 理解
    vue 中 $route 和 $router 的区别
    Vue + Element UI 实现权限管理系统 前端篇(十):动态加载菜单
    Vue + Element UI 实现权限管理系统 前端篇(九):接口格式定义
    Vue + Element UI 实现权限管理系统 前端篇(八):管理应用状态
    Vue + Element UI 实现权限管理系统 前端篇(七):功能组件封装
    [2020牛客暑期多校训练营(第十场)C Decrement on the Tree]
  • 原文地址:https://www.cnblogs.com/yjwamao/p/8810110.html
Copyright © 2011-2022 走看看