數據結構化與保存

1. 將新聞的正文內容保存到文本文件。php

def writeNewsDetails(contents):
    f = open('gzccnews.txt', 'a', encoding='utf-8')
    f.write(contents)
    f.close()

 

2. 將新聞數據結構化爲字典的列表:css

  • 單條新聞的詳情-->字典news
  • 一個列表頁全部單條新聞彙總-->列表newsls.append(news)
  • 全部列表頁的全部新聞彙總列表newstotal.extend(newsls)
    import requests
    from bs4 import BeautifulSoup
    from datetime import datetime
    import re
    import pandas
    import openpyxl
    import sqlite3
     
    url = "http://news.gzcc.cn/html/xiaoyuanxinwen/"
    res = requests.get(url);
    res.encoding = "utf-8"
    soup = BeautifulSoup(res.text,"html.parser");
     
    def writeNewsDetails(contents):
        f = open('gzccnews.txt',"a",encoding="utf-8")
        f.write(contents)
        f.close()
     
     
    def getClickCount(newUrl):
        newsId = re.findall("\_(.*).html",newUrl)[0].split("/")[-1];
        res = requests.get("http://oa.gzcc.cn/api.php?op=count&id= {}&modelid=80".format(newsId))
        return int(res.text.split(".html")[-1].lstrip("('").rsplit("');")[0])
     
     
    #獲取新聞詳情
    def getNewDetails(newsDetailUrl):
        detail_res = requests.get(newsDetailUrl)
        detail_res.encoding = "utf-8"
        detail_soup = BeautifulSoup(detail_res.text, "html.parser")
     
        news={}
        news['title'] = detail_soup.select(".show-title")[0].text
        info = detail_soup.select(".show-info")[0].text
        news['date_time'] = datetime.strptime(info.lstrip('發佈時間:')[:19], "%Y-%m-%d %H:%M:%S")
        if info.find('來源:')>0:
            news['source'] = info[info.find("來源:"):].split()[0].lstrip('來源:')
        else:
            news['source'] = 'none'
        news['content'] = detail_soup.select("#content")[0].text
        writeDetailNews(news['content'])
        news['click'] = getClickCount(newsDetailUrl)
        return news
        # print(news)
     
    # 獲取總頁數
    def getPageN(url):
        res = requests.get(url)
        res.encoding = 'utf-8'
        soup = BeautifulSoup(res.text, 'html.parser')
        return int(soup.select(".a1")[0].text.rstrip(""))//10+1
     
    # 獲取新聞一頁的全部信息
    def getListPage(url):
       newsList = []
       for news in soup.select("li"):
            if len(news.select(".news-list-title"))>0:  #排除爲空的li
                # time = news.select(".news-list-info")[0].contents[0].text
                # title = news.select(".news-list-title")[0].text
                # description = news.select(".news-list-description")[0].text
                detail_url = news.select('a')[0].attrs['href']
                newsList.append(getNewDetails(detail_url))
                return newsList
     
    newsTotal = []
    totalPageNum = getPageN(url)
    firstPageUrl = "http://news.gzcc.cn/html/xiaoyuanxinwen/"
    newsTotal.extend(getListPage(firstPageUrl))
     
    for num in range(totalPageNum,totalPageNum+1):
            listpageurl="http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html".format(num)
            getListPage(listpageurl)
     
    print(newsTotal)

     

3. 安裝pandas,用pandas.DataFrame(newstotal),建立一個DataFrame對象df.html

df = pandas.DataFrame(newsTotal)
print(df)

 

4. 經過df將提取的數據保存到csv或excel 文件。mysql

df.to_excel('gzcss.xlsx')

 

5. 用pandas提供的函數和方法進行數據分析:sql

  • 提取包含點擊次數、標題、來源的前6行數據
  • 提取‘學校綜合辦’發佈的,‘點擊次數’超過3000的新聞。
  • 提取'國際學院'和'學生工做處'發佈的新聞。
  • 進取2018年3月的新聞
    print(df[['title','clickCount','source']][:6])
     
    print(df[(df['clickCount']>3000)&(df['source']=='學校綜合辦')])
     
    sou = ['國際學院','學生工做處']
    print(df[df['source'].isin(sou)])
     
    # 進取2018年3月的新聞
    df1 = df.set_index('time')
    print(df1['2018-03'])

     

6. 保存到sqlite3數據庫數據庫

import sqlite3
with sqlite3.connect('gzccnewsdb.sqlite') as db:
df3.to_sql('gzccnews05',con = db, if_exists='replace')api

7. 從sqlite3讀數據數據結構

with sqlite3.connect('gzccnewsdb.sqlite') as db:
df2 = pandas.read_sql_query('SELECT * FROM gzccnews05',con=db)
print(df2)app

8. df保存到mysql數據庫函數

安裝SQLALchemy
安裝PyMySQL
MySQL裏建立數據庫:create database gzccnews charset utf8;

import pymysql
from sqlalchemy import create_engine
conn = create_engine('mysql+pymysql://root:root@localhost:3306/gzccnews?charset=utf8')
pandas.io.sql.to_sql(df, 'gzccnews', con=conn, if_exists='replace')

MySQL裏查看已保存了數據。(經過MySQL Client或Navicate。)

相關文章
相關標籤/搜索