数据结构化与保存

作业是转载同学的,因为没有对新闻信息做提取,所有无法添加新闻信息到字典。已练习pandas库的相关使用方法,导出excel文件。ps:自己的代码会尽快修改!

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



# 获取新闻点击次数
def getNewsId(url):
    newsId = re.findall(r'\_(.*).html', url)[0][-4:]
    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 writeNewsContentToFile(content):
    f=open('gzccNews.txt','a',encoding='utf-8')
    f.write(content)
    f.close()

# 获取新闻细节
def getNewsDetail(newsUrl):
    contentlist={}
    resd = requests.get(newsUrl)
    resd.encoding = 'utf-8'
    soupd = BeautifulSoup(resd.text, 'html.parser')
    newsDict = {}
    content = soupd.select('#content')[0].text
    writeNewsContentToFile(content)


    info = soupd.select('.show-info')[0].text
    newsDict['title'] = soupd.select('.show-title')[0].text

    # 识别时间格式
    date = re.search('(d{4}.d{2}.d{2}sd{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):
        newsDict['sources'] = re.search('来源:(.*)s*摄|点', info).group(1)
    else:
        newsDict['sources'] = 'none'
    if (info.find('摄影:') > 0):
        newsDict['photo'] = re.search('摄影:(.*)s*点', info).group(1)
    else:
        newsDict['photo'] = 'none'
    # 用datetime将时间字符串转换为datetime类型
    newsDict['dateTime'] = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')

    # 调用getNewsId()获取点击次数
    newsDict['click'] = getNewsId(newsUrl)

    return newsDict


def getListPage(listUrl):
    res = requests.get(listUrl)
    res.encoding = 'utf-8'
    soup = BeautifulSoup(res.text, 'html.parser')

    for new in soup.select('li'):
        if len(new.select('.news-list-title')) > 0:
            title = new.select('.news-list-title')[0].text
            description = new.select('.news-list-description')[0].text
            newsUrl = new.select('a')[0]['href']
            List = []
            print('标题:{0}
内容:{1}
链接:{2}'.format(title, description, newsUrl))
            # 调用getNewsDetail()获取新闻详情
            dict = getNewsDetail(newsUrl)
            List.append(dict)
            total.extend(List)


total = []
listUrl = 'http://news.gzcc.cn/html/xiaoyuanxinwen/'
getListPage(listUrl)
res = requests.get(listUrl)
res.encoding = 'utf-8'
soup = BeautifulSoup(res.text, 'html.parser')
listCount = int(soup.select('.a1')[0].text.rstrip(''))//10+1
df = pandas.DataFrame(total)
df.to_excel('newsresult.xlsx')
print(df[['click','author','dateTime','sources']][(df['click']>3000)&(df['sources'] == u'学生处')])
print(df[(df['click'] > 3000) & (df['sources'] == '学校综合办')])
print(df[['click', 'author', 'sources']].head(6))
news_info = ['国际学院', '学生工作处']
print(df[df['sources'].isin(news_info)])
原文地址:https://www.cnblogs.com/RE148/p/8810559.html