天天看點

爬取全部的校園新聞

改作業要求來源于:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE2/homework/2941

一、要求:

1.從新聞url擷取新聞詳情: 字典,anews

2.從清單頁的url擷取新聞url:清單append(字典) alist

3.生成所頁清單頁的url并擷取全部新聞 :清單extend(清單) allnews

*每個同學爬學号尾數開始的10個清單頁

4.設定合理的爬取間隔

import time

import random

time.sleep(random.random()*3)

5.用pandas做簡單的資料處理并儲存

儲存到csv或excel檔案 

newsdf.to_csv(r'F:\duym\爬蟲\gzccnews.csv')

儲存到資料庫

import sqlite3

with sqlite3.connect('gzccnewsdb.sqlite') as db:

    newsdf.to_sql('gzccnewsdb',db)

二、代碼及效果圖

1、從新聞url擷取新聞詳情: 字典,anews

def new(url):
    newDict={}
    res = requests.get(url)
    res.encoding = ('utf-8')
    soup = BeautifulSoup(res.text, 'html.parser')
    title = soup.select('.show-title')[0].text.split()
    author = soup.select('.show-info')[0].text.split()[2]
    auditor = soup.select('.show-info')[0].text.split()[3]
    newDict["title"]=title
    newDict["author"]=author
    newDict["auditor"]=auditor


    # 擷取點選次數
    clickurl = 'http://oa.gzcc.cn/api.php?op=count&id=11029&modelid=80'
    res2 = requests.get(clickurl)
    click = res2.text.split('.html')[-1].lstrip("('").rstrip("');")
    newDict["click"]=click

    # 擷取時間
    newsdate = soup.select('.show-info')[0].text.split()[0].split(':')[1]
    newstime = soup.select('.show-info')[0].text.split()[1]
    time = newsdate + ' ' + newstime
    time = datetime.strptime(time, '%Y-%m-%d %H:%M:%S')
    newDict["time"]=time

    p = print(title, '\n', author, '\n', auditor,  '\n', time, '\n', "點選:", click)
    return newDict
      

  

  效果圖:

爬取全部的校園新聞

2、從清單頁的url擷取新聞url:清單append(字典) alist

def alist(url):
    res = requests.get(listUrl)
    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]['href']
            newsData=new(newsUrl)
            newsList.append(newsData)
    return newsList
listUrl = 'http://news.gzcc.cn/html/xiaoyuanxinwen/'
print(alist(listUrl))
      
爬取全部的校園新聞

3、生成所頁清單頁的url并擷取全部新聞 :清單extend(清單) allnews

allnews=[]
for i in range(87,97):
    listUrl = 'http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html'.format(i)
    allnews.extend(alist(listUrl))
print(len(allnews))
      
爬取全部的校園新聞

4、設定合理的爬取間隔

for j in range(5):
        time.sleep(random.random()*3)
      

5、用pandas做簡單的資料處理并儲存

newsdf=pd.DataFrame(allnews)
newsdf.to_csv('new.csv')
      
爬取全部的校園新聞

6、儲存到資料庫

import sqlite3
with sqlite3.connect('gzccnewsdb.sqlite') as db:
    newsdf.to_sql('gzccnewsdb',db)