數據結構化與保存

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

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

  • 單條新聞的詳情-->字典news
  • 一個列表頁全部單條新聞彙總-->列表newsls.append(news)
  • 全部列表頁的全部新聞彙總列表newstotal.extend(newsls)
import requests
from bs4 import BeautifulSoup
from datetime import datetime
import re
import pandas
import sqlite3
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')




def writeNewsDetail(content):
    f = open('gzccNews.txt', 'a',encoding='utf-8')
    f.write(content)
    f.close()


def getClickCount(newsUrl):  #一篇新聞的點擊次數
    newId = re.search('\_(.*).html', newsUrl).group(1).split('/')[1]
    clickUrl = "http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80".format(newId)
    return (int(requests.get(clickUrl).text.split('.html')[-1].lstrip("('").rstrip("');")))


def getNewsDetail(newsUrl):  #一篇新聞的所有信息
    resd = requests.get(newsUrl)
    resd.encoding = 'utf-8'
    soupd = BeautifulSoup(resd.text, 'html.parser')  # 打開新聞詳情頁並解析

    news ={}
    news['title'] = soupd.select('.show-title')[0].text
    info = soupd.select('.show-info')[0].text
    news['dt'] = datetime.strptime(info.lstrip('發佈時間:')[0: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'] = soupd.select('.show-content')[0].text.strip()
    writeNewsDetail(news['content'])
    news['click'] = getClickCount(newsUrl)
    #print(dt,title,newsUrl,source,click)
    news['newsUrl'] = newsUrl
    return (news)


def getListPage(pageUrl):  #一個列表頁的所有新聞
    res = requests.get(pageUrl)
    res.encoding = 'utf-8'
    soup = BeautifulSoup(res.text, 'html.parser')

    newsList = []
    for news in soup.select('li'):
        if len(news.select('.news-list-title')) > 0:
            newsUrl = news.select('a')[0].attrs['href']  # 連接
            newsList.append(getNewsDetail(newsUrl))
    return(newsList)


def getPageN():  # 新聞列表頁的總頁數
    res = requests.get('http://news.gzcc.cn/html/xiaoyuanxinwen/')
    res.encoding = 'utf-8'
    soup = BeautifulSoup(res.text, 'html.parser')
    n = int(soup.select('.a1')[0].text.rstrip(''))
    return (n // 10 + 1)

newsTotal = []
firstPageUrl = 'http://news.gzcc.cn/html/xiaoyuanxinwen/'
newsTotal.extend(getListPage(firstPageUrl))




n = getPageN()
for i in range(n, n+1):
    listPageUrl = 'http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html'.format(i)
    newsTotal.extend(getListPage(listPageUrl))

print(newsTotal)

 

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

 

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

df=pandas.DataFrame(newsTotal)
df.to_excel('')

 

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

  • 提取包含點擊次數、標題、來源的前6行數據
  • 提取‘學校綜合辦’發佈的,‘點擊次數’超過3000的新聞。
  • 提取'國際學院'和'學生工做處'發佈的新聞。
  • 進取2018年3月的新聞
# 安裝pandas,用pandas.DataFrame(newstotal),建立一個DataFrame對象df.
df = pandas.DataFrame(newslist1)
print(df)
# 經過df將提取的數據保存到csv或excel 文件
df.to_csv("1.excel")
# 提取包含點擊次數、標題、來源的前5行數據
print(df[['click', 'title', 'sources']].head(5))
# 提取‘學校綜合辦’發佈的,‘點擊次數’超過3000的新聞。
print(df[(df['click'] > 3000) & (df['sources'] == '學校綜合辦')])
# 提取'國際學院'和'學生工做處'發佈的新聞。
print(df[df['sources'].isin(['國際學院', '學生工做處'])])
#進取2018年3月的新聞

print(df['dt']=='2018.03')

 

6. 保存到sqlite3數據庫api

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

7. 從sqlite3讀數據app

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

8. df保存到mysql數據庫spa

安裝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。)

相關文章
相關標籤/搜索