作业要求来自: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 def click(url): 6 id=re.findall('(d{1,5})',url)[-1] 7 clickUrl='http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80'.format(id) 8 resClick=requests.get(clickUrl) 9 newsClick=int(resClick.text.split('.html')[-1].lstrip("('").rstrip("');")) 10 return newsClick 11 def newsdt(showinfo): 12 newsDate=showinfo.split()[0].split(":")[1] 13 newsTime=showinfo.split()[1] 14 newsDT=newsDate+' '+newsTime 15 dt=datetime.strptime(newsDT,'%Y-%m-%d %H:%M:%S') 16 return dt 17 def anews(url): 18 newsDetail={} 19 res=requests.get(url) 20 res.encoding='utf-8' 21 soup=BeautifulSoup(res.text,'html.parser') 22 newsDetail['nenewsTitle']=soup.select('.show-title')[0].text 23 showinfo=soup.select('.show-info')[0].text 24 newsDetail['newsDT']=newsdt(showinfo) 25 newsDetail['newsClick']=click(newsUrl) 26 return newsDetail 27 newsUrl='http://news.gzcc.cn/html/2005/xiaoyuanxinwen_0710/4.html' 28 anews(newsUrl) 29 res = requests.get('http://news.gzcc.cn/html/xiaoyuanxinwen/') 30 res.encoding='utf-8' 31 soup = BeautifulSoup(res.text,'html.parser') 32 for news in soup.select('li'): 33 if len(news.select('.news-list-title'))>0: 34 newsUrl=news.select('a')[0]['href'] 35 print(anews(newsUrl))
运行结果:
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 newsList
运行结果:
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(101,111): 19 listUrl='http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html'.format(i) 20 allnews.extend(alist(listUrl)) 21 len(allnews)
运行结果:
4.设置合理的爬取间隔
import time
import random
time.sleep(random.random()*3)
5.用pandas做简单的数据处理并保存
保存到csv或excel文件
newsdf.to_csv(r'F:duym爬虫gzccnews2.csv')
保存到数据库
import sqlite3
with sqlite3.connect('gzccnewsdb.sqlite') as db:
newsdf.to_sql('gzccnewsdb',db)