import requests
from bs4 import BeautifulSoup
from datetime import datetime
import re
import pandas
#====================================================================
#3-1. 将新闻的正文内容保存到文本文件。
#====================================================================
def record(text):
f=open('cratch.txt','a',encoding='utf-8')
f.write(text)
f.close()
#===================================================================
#3-2. 将新闻数据结构化为字典的列表:
#===================================================================
#3-2-1. 单条新闻的详情-->字典news
#3-2-2.一个列表页所有单条新闻汇总-->列表newsls.append(news)
def getList(pageUrl):
res=requests.get(pageUrl)
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].attrs['href']
newsList.append(getNewsDetail(newsUrl))
print(newsList)
return newsList
#3-2-3.所有列表页的所有新闻汇总列表newstotal.extend(newsls)
def getPageN():
res=requests.get('http://news.gzcc.cn/html/xiaoyuanxinwen/')
res.encoding='utf-8'
soup=BeautifulSoup(res.text,'html.parser')
n=int(soup.select('.a1')[0].text.rstrip('条'))
return(n//10+1)
newsTotal=[]
n=getPageN()
p= [2, n]
for i in p:
listPageUrl = "http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html".format(i)
print(listPageUrl)
newsTotal.extend(getListPage(listPageUrl))
for news in newsTotal:
print(news)
#===================================================================
#3. 安装pandas,用pandas.DataFrame(newstotal),创建一个DataFrame对象df.
#===================================================================
df=pandas.DataFrame(newsTotal)
#===================================================================
#4. 通过df将提取的数据保存到csv或excel 文件。
#===================================================================
df.to_excel("0416.xlsx")
#===================================================================
#5. 用pandas提供的函数和方法进行数据分析:
# 提取包含点击次数、标题、来源的前6行数据
# 提取‘学校综合办’发布的,‘点击次数’超过3000的新闻。
# 提取'国际学院'和'学生工作处'发布的新闻。
#===================================================================
print(df[['count','title','source']][0:6])
print(df[(df['count']>3000)&(df['source']=='学校综合办')])
print(df[(df['source']=='国际学院')|(df['source']=='学生处')])