天天看點

爬取全部的校園新聞

本次作業的要求來自于:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE1/homework/3002

0.從新聞url擷取點選次數,并整理成函數

  • newsUrl
  • newsId(re.search())
  • clickUrl(str.format())
  • requests.get(clickUrl)
  • re.search()/.split()
  • str.lstrip(),str.rstrip()
  • int
  • 整理成函數
  • 擷取新聞釋出時間及類型轉換也整理成函數

1.熟練運用re.search(),match(),findall()

爬取全部的校園新聞

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

import requests
from bs4 import BeautifulSoup
from datetime import datetime
import re
def click(url):
id=re.findall('(\d+)',url)[-1]
clickurl='http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80'.format(id)
resclick=requests.get(clickurl)
newsclick=int(resclick.text.split(".html")[-1].lstrip("('").rstrip("');"))
return newsclick
def newsdt(showinfo):
newsdate=showinfo.split()[0].split(':')[1]
newstime=showinfo.split()[1]
newsDT=newsdate+' '+newstime
dt=datetime.strptime(newsDT,'%Y-%m-%d %H:%M:%S')
return dt
def anews(url):
newsdetail={}
res=requests.get(url)
res.encoding='utf-8'
soup=BeautifulSoup(res.text,'html.parser')
newsdetail['nenewstitle']=soup.select('.show-title')[0].text
showinfo=soup.select('.show-info')[0].text 
newsdetail['newsDT']=newsdt(showinfo)
newsdetail['newsclick']=click(newsurl)
return newsdetail

def alist(listurl):
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']
newsdesc = news.select('.news-list-description')[0].text
newsdict = anews(newsurl)
newsdict['newsurl'] = newsurl
newsdict['descricption'] = newsdesc
newslist.append(newsdict)
return newslist

listurl='http://news.gzcc.cn/html/xiaoyuanxinwen/'
alist(listurl)
      

  

截圖:

爬取全部的校園新聞

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

爬取全部的校園新聞

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

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

res=requests.get('http://news.gzcc.cn/html/xiaoyuanxinwen/')
res.encoding='utf-8'
soup=BeautifulSoup(res.text,'html.parser')
soup.select('#pages')[0].text

int(re.search('..(\d+).下',soup.select('#pages')[0].text).groups(1)[0])

listurl='http://news.gzcc.cn/html/xiaoyuanxinwen/'
allnews=alist(listurl)

for i in range(5,15):
    listurl='http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html'.format(i)
    allnews.extend(alist(listurl))
    
      

爬取一頁;

爬取全部的校園新聞

爬取多頁;

爬取全部的校園新聞

5.設定合理的爬取間隔

import time

import random

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

import time
import random

for i in range(1,3):
    print(i)
    time.sleep(random.random()*3)#休眠随機數的3倍時間

print(tenNews)
      

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

儲存到csv或excel檔案 

newsdf.to_csv(r'E:\gzcc.csv')      
import pandas as pd
newsdf = pd.DataFrame(allnews)


newsdf.to_csv(r'E:\gzcc.csv')      

截圖:圖為(5-15頁内容)

爬取全部的校園新聞
爬取全部的校園新聞