本次做業要求來自於:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE1/homework/3002php
程序準備:html
# 導入須要用到的類包 import re import requests from bs4 import BeautifulSoup from datetime import datetime import time import random import pandas as pd
0.重新聞url獲取點擊次數,並整理成函數api
# 新聞點擊次數 def clickCounts(url): id = re.findall('\d+',url)[-1] clickUrl = "http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80".format(id) clickStruct = requests.get(clickUrl).text clickCounts = int(clickStruct.split('.html')[-1][2:-3]) return clickCounts
1.重新聞url獲取新聞詳情: 字典,anews app
# 新聞的發佈時間 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['newsTitle'] = soup.select('.show-title')[0].text showInfo = soup.select('.show-info')[0].text newsDetail['newsDT'] = newsdt(showInfo) newsDetail['newsClick'] = clickCounts(url) return newsDetail
# 測試爬出一篇新聞報道的概況 newsUrl = "http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0404/11155.html" print(anews(newsUrl))
運行示例:dom
2.從列表頁的url獲取新聞url:列表append(字典) alist 函數
# 從列表頁的url獲取新聞url 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['description'] = newsDesc newsList.append(newsDict) return newsList # 測試爬出一頁新聞報道的概況 listUrl = 'http://news.gzcc.cn/html/xiaoyuanxinwen/' allnews = alist(listUrl) for newtro in allnews: print(newtro)
運行示例:測試
3.生成全部列表頁的url並獲取所有新聞 :列表extend(列表) allnews網站
*每一個同窗爬學號尾數開始的10個列表頁url
# 爬學號尾數開始的10個列表頁 allnews = [] for i in range(25,35): listUrl = 'http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html'.format(i) allnews.extend(alist(listUrl)) # 測試爬出所在網站所選頁新聞報道的概況 for n in allnews: print(n) print(len(allnews))#統計所爬取的新聞總數
運行示例:spa
4.設置合理的爬取間隔
import time
import random
time.sleep(random.random()*3)
5.用pandas作簡單的數據處理並保存
保存到csv或excel文件
# 用pandas作簡單的數據處理 newsdf = pd.DataFrame(allnews) for i in range(5): print(i) time.sleep(random.random() * 3)#設置時間間隔爬取並輸出到控制檯 print(newsdf) # 保存到本地csv文件 newsdf.to_csv(r'D:\gzccnews.csv',encoding='utf-8')
運行示例:
......