爬取全部的校园新闻

1.从新闻url获取新闻详情: 字典,anews

 1 # -*- coding: utf-8 -*-
 2 """
 3 Spyder Editor
 4 
 5 This is a temporary script file.
 6 """
 7 import requests
 8 from bs4 import BeautifulSoup
 9 from datetime import datetime
10 import re
11 
12 def click(url):
13     id = re.findall('(\d{1,5})',url)[-1]
14     clickUrl='http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80'.format(id)
15     resClick = requests.get(clickUrl)
16     newsClick = int(resClick.text.split('.html')[-1].lstrip("('").rstrip("');"))
17     return newsClick
18 
19 def newsdt(showinfo):
20     newsDate = showinfo.split()[0].split(':')[1]
21     newsTime = showinfo.split()[1]
22     newDT = newsDate+' '+newsTime
23     dt = datetime.strptime(newDT,'%Y-%m-%d %H:%M:%S')
24     return dt
25 
26 def anews(url):
27     newsDetail = {}
28     res = requests.get(url)
29     res.encoding = 'utf-8'
30     soup = BeautifulSoup(res.text,'html.parser')
31     newsDetail['nenewsTitle'] = soup.select('.show-title')[0].text
32     showinfo = soup.select('.show-info')[0].text
33     newsDetail['newsDT'] = newsdt(showinfo)
34     newsDetail['newsClick'] = click(newsUrl)
35     return newsDetail
36 
37 newsUrl = 'http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0404/11155.html'
38 anews(newsUrl)
39 
40 res=requests.get('http://news.gzcc.cn/html/xiaoyuanxinwen')
41 res.encoding='utf-8'
42 soup = BeautifulSoup(res.text,'html.parser') 
43 
44 for news in soup.select('li'):
45     if len(news.select('.news-list-title'))>0:
46         newsUrl = news.select('a')[0]['href']
47         print(anews(newsUrl))
View Code

 

2.从列表页的url获取新闻url:列表append(字典) alist

 1 listUrl='http://news.gzcc.cn/html/xiaoyuanxinwen/'
 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 print(newsList)
View Code

 

3.生成所页列表页的url并获取全部新闻 :列表extend(列表) allnews

*每个同学爬学号尾数开始的10个列表页

 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(78,88):
19     listUrl='http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html'.format(i)
20     allnews.extend(alist(listUrl))
21 len(allnews)
22 print(allnews)
View Code

4.设置合理的爬取间隔

 1 allnews=[]
 2 for i in range(78,88):
 3     listUrl='http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html'.format(i)
 4     allnews.extend(alist(listUrl))
 5 len(allnews)
 6 
 7 pd.Series(anews)
 8 newsdf=pd.DataFrame(allnews)
 9 for i in range(5):
10     print(i)
11     time.sleep(random.random()*3)        
12     print(newsdf)
View Code

 

5.用pandas做简单的数据处理并保存

保存到csv或excel文件 

1 newsdf.to_csv(r'F:\hhhh.csv')

 

保存到数据库

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

 

posted @ 2019-04-08 17:10  huangzhenjie  阅读(170)  评论(0编辑  收藏  举报