爬取所有的校園新聞

 

爬取所有的校園新聞

做業要求來自於https://edu.cnblogs.com/campus/gzcc/GZCC-16SE2/homework/2941php

 

1.重新聞url獲取新聞詳情: 字典,anews html

代碼以下: sql

 

 1 import requests
 2 from bs4 import BeautifulSoup
 3 from datetime import datetime
 4 import re
 5 
 6 def click(url):
 7     id = re.findall('(\d{1,5})',url)[-1]#返回全部匹配的字符串的字符串列表的最後一個
 8     clickUrl = 'http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80'.format(id)
 9     resClick = requests.get(clickUrl)
10     newsClick = int(resClick.text.split('.html')[-1].lstrip("('").rstrip("');"))
11     return newsClick
12 
13 def newsdt(showinfo):
14     newsDate = showinfo.split()[0].split(':')[1]
15     newsTime = showinfo.split()[1]
16     newsDT = newsDate+' '+newsTime
17     dt = datetime.strptime(newsDT,'%Y-%m-%d %H:%M:%S')#轉換成datetime類型
18     return dt
19 
20 def anews(url):
21     newsDetail = {}
22     res = requests.get(url)
23     res.encoding = 'utf-8'
24     soup = BeautifulSoup(res.text,'html.parser')
25     newsDetail['newsTitle'] = soup.select('.show-title')[0].text#題目
26     showinfo = soup.select('.show-info')[0].text
27     newsDetail['newsDT'] = newsdt(showinfo)#時間
28     newsDetail['newsClick'] = click(newsUrl)#點擊次數
29     return newsDetail
30 newsUrl = 'http://news.gzcc.cn/html/2018/xiaoyuanxinwen_1217/10704.html'
31 print(anews(newsUrl))
new1

運行截圖: 數據庫

 

2.從列表頁的url獲取新聞url:列表append(字典) alist api

代碼以下: 數組

 

 1 def anews(url):
 2     newsDetail = {}
 3     res = requests.get(url)
 4     res.encoding = 'utf-8'
 5     soup = BeautifulSoup(res.text,'html.parser')
 6     newsDetail['newsTitle'] = soup.select('.show-title')[0].text#題目
 7     return newsDetail
 8 def alist(url):
 9     res=requests.get(listUrl)
10     res.encoding='utf-8'
11     soup = BeautifulSoup(res.text,'html.parser')
12     newsList=[]
13     for news in soup.select('li'):
14         if len(news.select('.news-list-title'))>0:
15             newsUrl=news.select('a')[0]['href']
16             newsDesc=news.select('.news-list-description')[0].text
17             newsDict=anews(newsUrl)
18             newsDict['description']=newsDesc
19             newsList.append(newsDict)
20     return newsList
21 listUrl='http://news.gzcc.cn/html/xiaoyuanxinwen/'
22 alist(listUrl)
new2

運行截圖: 數據結構

 

3.生成所頁列表頁的url並獲取所有新聞 :列表extend(列表) allnews app

*每一個同窗爬學號尾數開始的10個列表頁dom

代碼以下: ide

 

 1 def alist(url):
 2     res=requests.get(listUrl)
 3     res.encoding='utf-8'
 4     soup = BeautifulSoup(res.text,'html.parser')
 5     newsList=[]
 6     for news in soup.select('li'):
 7         if len(news.select('.news-list-title'))>0:
 8             newsUrl=news.select('a')[0]['href']
 9             newsDesc=news.select('.news-list-description')[0].text
10             newsDict=anews(newsUrl)
11             newsDict['description']=newsDesc
12             newsList.append(newsDict)
13     return newsList
14 listUrl='http://news.gzcc.cn/html/xiaoyuanxinwen/'
15 alist(listUrl)
16 
17 allnews=[]
18 for i in range(83,93):
19     listUrl='http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html'.format(i)
20     allnews.extend(alist(listUrl))
21 
22 for i in range(5):
23     print(i)
24     time.sleep(random.random()*3)#沉睡隨機數的3倍秒數
25 print(allnews)
new3

運行截圖:

 

 

4.設置合理的爬取間隔

import time

import random

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

代碼以下:

 

1 for i in range(5):
2     print(i)
3     time.sleep(random.random()*3)#沉睡隨機數的3倍秒數
4 print(allnews)
sleep

運行截圖:

 

 

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 newsUrl = 'http://news.gzcc.cn/html/2018/xiaoyuanxinwen_1217/10704.html'
 2 s2 = pd.Series(anews(newsUrl))#一維數組對象
 3 print(s2)
 4 newsdf = pd.DataFrame(allnews)#表格型的數據結構
 5 print(newsdf)
 6 pd.DataFrame(data=newsdf).to_csv('news.csv',encoding='utf_8_sig')
 7 
 8 with sqlite3.connect('gzccnewsdb.sqlite') as db:
 9     newsdf.to_sql('gzccnewsdb',db)
10 with sqlite3.connect('gzccnewsdb.sqlite') as db:
11     df2 = pandas.read_sql_query('SELECT * FROM gzccnewsdb',con=db)
new5

運行截圖:

 

相關文章
相關標籤/搜索