数据结构化与保存

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

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

  

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

(1)单条新闻的详情-->字典news

        

def getNewDetail(a):
    newsdict={}
    resd = requests.get(a)
    resd.encoding = 'utf-8'
    soupd = BeautifulSoup(resd.text, 'html.parser')
    newsdict['title'] = soupd.select('.show-title')[0].text
    info = soupd.select('.show-info')[0].text
    d= info.lstrip('发布时间:')[:19]
    newsdict['a']=a
    newsdict['dateTime'] = datetime.strptime(d, '%Y-%m-%d %H:%M:%S')
    newsdict['author'] = info[info.find('作者:'):].split()[0].lstrip('作者:')
    newsdict['source'] = info[info.find('来源:'):].split()[0].lstrip('来源:')
    newsdict['photo'] = info[info.find('摄影:'):].split()[0].lstrip('摄影:')
    newsdict['clickcount'] = getClickCount(a)
    return newsdict

  

  

(2)一个列表页所有单条新闻汇总-->列表newsls.append(news)

          

def listPage(pageUrl):
    newsls = []
    res = requests.get(pageUrl)  # 返回response对象
    res.encoding = 'utf-8'
    soup = BeautifulSoup(res.text, 'html.parser')
    for news in soup.select('li'):
        if len(news.select('.news-list-title')) > 0:
            a = news.select('a')[0].attrs['href']  # 链接
            newsls.append(getNewDetail(a))
    return newsls

  

(3)所有列表页的所有新闻汇总列表newstotal.extend(newsls)

        

def getpagelist(path):
    res = requests.get(path)  # 返回response对象
    res.encoding = 'utf-8'
    soup = BeautifulSoup(res.text, 'html.parser')
    newsnum = int(soup.select('.a1')[0].text.rstrip('条'))  # 新闻总条数
    if (newsnum % 10 == 0):
        totalpage = newsnum // 10
    else:
        totalpage = newsnum // 10 + 1  # 新闻总页数

    for i in range(1, totalpage):
        pageUrl = path + '{}.html'.format(i)
        newstotal.append(listPage(pageUrl))

  

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

import pandas
df = pandas.DataFrame(newstotal)

  

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

df.to_excel('gzccnews.xlsx')

  

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

(1)提取包含点击次数、标题、来源的前6行数据

df[['clickcount', 'title', 'source']].head(6)
print(df[['clickcount', 'title', 'source']].head(6))

  

(2)提取‘学校综合办’发布的,‘点击次数’超过3000的新闻。

        

df[(df['clickcount'] > 3000) & (df['source'] == '学校综合办')]
print(df[(df['clickcount'] > 3000) & (df['source'] == '学校综合办')])

(3)提取'国际学院'和'学生工作处'发布的新闻。

         

soulist = ['国际学院', '学生工作处']
print(df[df['source'].isin(soulist)]

  

原文地址:https://www.cnblogs.com/1996-yxl/p/8807921.html