數據結構化與保存

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

import requests
from bs4 import BeautifulSoup

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()

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

  • 單條新聞的詳情-->字典news
  • 一個列表頁全部單條新聞彙總-->列表newsls.append(news)
  • 全部列表頁的全部新聞彙總列表newstotal.extend(newsls)
    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
        news['click'] = getClickCount(newsDetailUrl)
        return 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:
                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)

     

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)])
    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')

7. 從sqlite3讀數據api

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

8. df保存到mysql數據庫數據結構

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

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

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')
相關文章
相關標籤/搜索