爬取全部的校园新闻

 

爬取全部的校园新闻

作业要求来自于https://edu.cnblogs.com/campus/gzcc/GZCC-16SE2/homework/2941

 

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

代码如下:

 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

代码如下:

 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

*每个同学爬学号尾数开始的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(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

运行截图:

 

原文地址:https://www.cnblogs.com/lys1894/p/10698577.html