作业:爬取全部的校园新闻

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

 

我爬取的网页是某高校的新闻信息网站:http://news.gzcc.cn/html/2005/xiaoyuanxinwen_0710/4.html。

代码如下:

# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""

import pymysql
from sqlalchemy import create_engine
import requests
from bs4 import BeautifulSoup
from datetime import datetime
import re
import pandas as pd
import sqlite3
import time
import random

def click(url):
id=re.findall('(\d{1,5})',url)[-1]
clickUrl='http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80'.format(id)
resClick=requests.get(clickUrl)
newsClick=int(resClick.text.split('.html')[-1].lstrip("('").rstrip("');"))
return newsClick

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['nenewsTitle']=soup.select('.show-title')[0].text
showinfo=soup.select('.show-info')[0].text
newsDetail['newsDT']=newsdt(showinfo)
newsDetail['newsClick']=click(url)
return newsDetail

def alist(url):
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['description']=newsDesc
newsList.append(newsDict)
return newsList

listUrl='http://news.gzcc.cn/html/xiaoyuanxinwen/'
alist(listUrl)
res=requests.get(listUrl)
res.encoding='utf-8'
soup=BeautifulSoup(res.text,'html.parser')
for n in soup.select('li'):
if n.select('.news-list-title'):
print(n.select('a')[0]['href'])

i=int(soup.select('#pages')[0].text.split('..')[1].rstrip(' 下一页 '))
allnews=[]
for i in range(99,109): #爬取校园网有限范围的新闻内容
listUrl='http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html'.format(i)
allnews.extend(alist(listUrl))
len(allnews)
print(allnews)

newsUrl='http://news.gzcc.cn/html/2005/xiaoyuanxinwen_0710/4.html'
anews(newsUrl)

res=requests.get('http://news.gzcc.cn/html/xiaoyuanxinwen/')
res.encoding='utf-8'
soup=BeautifulSoup(res.text,'html.parser')
for news in soup.select('li'):
if len(news.select('.news-list-title'))>0:
newsUrl=news.select('a')[0]['href']
print(anews(newsUrl))

s1=pd.Series([100,23,'bugingcode'])
print(s1)
pd.Series(anews)
newsdf=pd.DataFrame(allnews)
for i in range(5):
print(i)
time.sleep(random.random()*3) #设置合理的爬取间隔
print(newsdf)

newsdf.to_excel('123.xlsx') #在本地项目下生成一个表格存储爬取新闻内容

conInfo = "mysql+pymysql://root:@localhost:3306/gzccnewsdb?charset=utf8"
engine = create_engine(conInfo,encoding='utf-8')
newsdf.to_sql(name='news',con=engine,if_exists='append',index=False,index_label='id')
pymysql.connect(host='localhost',port=3306,user='root',passwd='',db='gzccnewsdb',charset='utf8')

 

代码运行效果如下:

 

将新闻内容存储到Excel表中,效果如下:

 

将新闻内容存储到数据库中,效果如下:

 

posted @ 2019-04-08 16:04  林溢漫  阅读(352)  评论(0编辑  收藏  举报