博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
爬取全部的校园新闻
阅读量:7117 次
发布时间:2019-06-28

本文共 4518 字,大约阅读时间需要 15 分钟。

作业要求来自于:

0.从新闻url获取点击次数,并整理成函数

  • newsUrl
  • newsId(re.search())
  • clickUrl(str.format())
  • requests.get(clickUrl)
  • re.search()/.split()
  • str.lstrip(),str.rstrip()
  • int
  • 整理成函数
  • 获取新闻发布时间及类型转换也整理成函数

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

import pandasimport requestsfrom bs4 import BeautifulSoupfrom datetime import datetimeimport redef 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')#转换成datetime类型    return dt#内容def anews(url):    newsDetail = {}    res = requests.get(url)    res.encoding = 'utf-8'    soup = BeautifulSoup(res.text,'html.parser')    newsDetail['newsTitle'] = soup.select('.show-title')[0].text#题目    showinfo = soup.select('.show-info')[0].text    newsDetail['newsDT'] = newsdt(showinfo)#时间    newsDetail['newsClick'] = click(newsUrl)#点击次数    return newsDetailnewsUrl = 'http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0404/11155.html'print(anews(newsUrl))anews

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

 

import pandasimport requestsfrom bs4 import BeautifulSoupfrom datetime import datetimeimport redef 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 newsClickdef 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')#转换成datetime类型    return dtdef anews(url):    newsDetail = {}    res = requests.get(url)    res.encoding = 'utf-8'    soup = BeautifulSoup(res.text,'html.parser')    newsDetail['newsTitle'] = soup.select('.show-title')[0].text#题目    showinfo = soup.select('.show-info')[0].text    newsDetail['newsDT'] = newsdt(showinfo)#时间    newsDetail['newsClick'] = click(newsUrl)#点击次数    return newsDetaildef alist(url):    res = requests.get(listUrl)    res.encoding = 'utf-8'    soup = BeautifulSoup(res.text, 'html.parser')    newsList = []    for news in soup.select('li'):#获取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 newsListlistUrl = 'http://news.gzcc.cn/html/xiaoyuanxinwen/'print(alist(listUrl))alist

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

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

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 newsListlistUrl='http://news.gzcc.cn/html/xiaoyuanxinwen/'alist(listUrl)allnews=[]for i in range(40,50):    listUrl='http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html'.format(i)    allnews.extend(alist(listUrl))len(allnews)

 

 

 

4.设置合理的爬取间隔

import time

import random

time.sleep(random.random()*3)

 

import timeimport randomfor i in range(5):    print(i)    time.sleep(random.random()*3)#沉睡随机数的3倍秒数print(allnews)

 

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

保存到csv或excel文件 

newsdf.to_csv(r'F:\duym\爬虫\gzccnews.csv')

import pandas as pds2 = pd.Series(anews(newsUrl))#一维数组对象print(s2)newsdf = pd.DataFrame(allnews)#表格型的数据结构print(newsdf)print(newsdf.sort_values(by=['newsDT'],ascending=False))#按更新时间降序排列print(newsdf.sort_index(by=['newsClick'],ascending=False))#按点击量降序排列newsdf.to_csv(r'gzccnews.csv')import sqlite3with sqlite3.connect('gzccnewsdb.sqlite') as db:    newsdf.to_sql('gzccnewsdb',db)with sqlite3.connect('gzccnewsdb.sqlite') as db:    df2 = pandas.read_sql_query('SELECT * FROM gzccnewsdb',con=db)print(df2[df2['newsClick']>385])
newsdf.to_csv(r'F:\gzccnews.csv')

 

 

 

转载于:https://www.cnblogs.com/lxyu/p/10696654.html

你可能感兴趣的文章
httpclient调用https
查看>>
Oracle数据库中有关记录个数的查询
查看>>
sql语句查询出表里符合条件的第二条记录的方法
查看>>
题目1008:最短路径问题
查看>>
PHPExcel正确读取excel表格时间单元格(转载)
查看>>
继电器是如何成为CPU的
查看>>
分布式缓存
查看>>
Android-ViewPager+Fragment数据更新问题
查看>>
[WASM] Compile C Code into WebAssembly
查看>>
JAVA8-让代码更优雅之List排序
查看>>
为什么我的淘宝排名会突然下降?
查看>>
SecureCRT常用快捷键
查看>>
java使用Rome解析Rss的实例(转)
查看>>
零基础 Vue 开发环境搭建 打开运行Vue项目
查看>>
tensorflow 笔记12:函数区别:placeholder,variable,get_variable,参数共享
查看>>
(转)漫谈MySql中的事务
查看>>
将逗号分隔的字符串与List互转
查看>>
MongoDB下Map-Reduce使用简单翻译及示例
查看>>
Model Metadata
查看>>
对象图(Object Diagram)—UML图(三)
查看>>