数据结构化与保存

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

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

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

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

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

import requests
from bs4 import BeautifulSoup
from datetime import datetime
import re
import pandas
import openpyxl
url = 'http://news.gzcc.cn/html/xiaoyuanxinwen/'
res = requests.get(url)
res.encoding = 'utf-8'
soup = BeautifulSoup(res.text, 'html.parser')


def getClick(newsUrl):
    newId = re.search('\_(.*).html', newsUrl).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 getNews(newsUrl):
    resd = requests.get(newsUrl)
    resd.encoding = 'utf-8'
    soupd = BeautifulSoup(resd.text, 'html.parser')
    newsDict = {}
    info = soupd.select('.show-info')[0].text
    newsDict['title'] = soupd.select('.show-title')[0].text
    dt = datetime.strptime(info.lstrip('发布时间:')[0:19], '%Y-%m-%d %H:%M:%S')
    if (info.find('作者:') > 0):
        newsDict['author'] = re.search('作者:((.{2,4}s|.{2,4}、){1,3})', info).group(1)
    if (info.find('审核:') > 0):
        newsDict['check'] = re.search('审核:((.{2,4}s){1,3})', info).group(1)
    if (info.find('来源:') > 0):
        newsDict['sources'] = re.search('来源:((.{2,50}s|.{2,50}、|.{2,50},){1,5})', info).group(1)
    content = soupd.select('.show-content')[0].text.strip()
    click = getClick(newsUrl)
    # print(click,title,newsUrl,author,check,sources,dt)
    newsDict['click'] = getClick(newsUrl)  # 调用getnewsclick()获取点击次数
    newsDict['content'] = content
    return newsDict



def getListPage(listPageUrl):
    res=requests.get(listPageUrl)
    res.encoding='utf-8'
    soup=BeautifulSoup(res.text,'html.parser')
    pagelist = []
    for news in soup.select('li'):
        if len(news.select('.news-list-title')) > 0:
            a = news.select('a')[0]['href']
            pagedict = getNews(a)  # 调用getnewsdetail()获取新闻详情
            pagelist.append(pagedict)
    return pagelist

# listPageUrl='http://news.gzcc.cn/html/xiaoyuanxinwen/'
resn = requests.get('http://news.gzcc.cn/html/xiaoyuanxinwen/')
resn.encoding = 'utf-8'
soupn = BeautifulSoup(resn.text,'html.parser')
n = int(soupn.select('.a1')[0].text.rstrip(''))//10+1
total = []
listPageUrl = 'http://news.gzcc.cn/html/xiaoyuanxinwen/'
pagelist = getListPage(listPageUrl)
total.extend(pagelist)
pan = pandas.DataFrame(total)
pan.to_excel('result.xlsx')  # 导出为Excel表格
pan.to_csv('result.csv')  # 导出为csv文件
for i in range(2,4):
    listPageUrl='http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html'.format(i)
    getListPage(listPageUrl)

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

  • 提取包含点击次数、标题、来源的前6行数据
  • 提取‘学校综合办’发布的,‘点击次数’超过3000的新闻。
  • 提取'国际学院'和'学生工作处'发布的新闻。
    print(pan[(pan['click'] > 3000) & (pan['sources'] == '学校综合办')])
    print(pan[['click', 'author', 'sources']].head(6))
    news_info = ['国际学院', '学生工作处']
    print(pan[pan['sources'].isin(news_info)])
原文地址:https://www.cnblogs.com/170he/p/8810248.html