博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
数据结构化与保存
阅读量:4670 次
发布时间:2019-06-09

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

1. 将新闻的正文内容保存到文本文件。def writeFile(content):    f = open('gzccnews.txt','a',encoding='utf-8')    f.write(content)    f.close()

  

2. 将新闻数据结构化为字典的列表:单条新闻的详情-->字典news一个列表页所有单条新闻汇总-->列表newsls.append(news)所有列表页的所有新闻汇总列表newstotal.extend(newsls)def getClickCount(newsUrl):    newId = re.search('\_(.*).html', newsUrl).group(1).split('/')[-1]    res = requests.get('http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80'.format(newId))    res.encoding = 'utf-8'    count = int(res.text.split('.html')[-1].lstrip("('").rstrip("');"))    return countdef getNewDetail(newsUrl):    res = requests.get(newsUrl)    res.encoding = 'utf-8'    soup = BeautifulSoup(res.text, 'html.parser')    news = {}    news['title'] = soup.select('.show-title')[0].text    # info = soup.select('.show-info')[0].text.split()    info = soup.select('.show-info')[0].text    content = soup.select('#content')[0].text    # writeFile(content)    # print(soup.select('#content')[0].text)    s = info.split()[0].lstrip('发布时间:') + " " + info.split()[1]  # 发布时间    # zz = info[2].lstrip('作者:')  #作者    # sh = info[3].lstrip('审核:')  #审核    # ly = info[4].lstrip("来源:")  #来源    if info.find('来源:') > 0:        news['source'] = info[info.find('来源:'):].split()[0].lstrip('来源:')    else:        news['source'] = 'none'    news['time'] = datetime.strptime(s, '%Y-%m-%d %H:%M:%S')    news['clickCount'] = getClickCount(newsUrl)    news['newsUrl']= newsUrl    # print(cc,type(cc))    print(news)    return newsdef getListPage(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:            a = news.select('a')[0].attrs['href']  # URL            newslist.append(getNewDetail(a))    return newslist  def getPageN():    res = requests.get('http://news.gzcc.cn/html/xiaoyuanxinwen/')    res.encoding = 'utf-8'    soup = BeautifulSoup(res.text, 'html.parser')    pagenumber=int(soup.select('.a1')[0].text.rstrip('条'))    page = pagenumber//10+1    return page  print(getPageN()) firstUrl = 'http://news.gzcc.cn/html/xiaoyuanxinwen'res = requests.get(firstUrl)res.encoding = 'utf-8' n=getPageN()newstotal = []for i in range(2,4):    print(i)    listPageUrl='http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html'.format(i)    temp = getListPage(listPageUrl)    newstotal.extend(temp)

  

3. 安装pandas,用pandas.DataFrame(newstotal),创建一个DataFrame对象df.import pandasdf = pandas.DataFrame(newstotal)

  

4. 通过df将提取的数据保存到csv或excel 文件。import openpyxldf.to_excel('df_to_excel.xlsx')

  

5. 用pandas提供的函数和方法进行数据分析:1、提取包含点击次数、标题、来源的前6行数据2、提取‘学校综合办’发布的,‘点击次数’超过3000的新闻。3、提取'国际学院'和'学生工作处'发布的新闻。4、提取2018年3月的新闻1、print(df[['clickCount','title','source']].head(6)) 1:截图
 
2、
print
(df[(df[
'clickCount'
]>
3000
)&(df[
'source'
]
=
=
'学校综合办'
)])
 

  

print(df[(df['source']=='国际学院')|(df['source']=='学生工作处')])

  

3、截图

4、print(df1['2018-04-11'])

 

6. 保存到sqlite3数据库import sqlite3with sqlite3.connect('gzccnewsdb.sqlite') as db:    df.to_sql('gzccnews11',con=db,if_exists='replace')

  

7. 从sqlite3读数据with sqlite3.connect('gzccnewsdb.sqlite') as db:    df10 = pandas.read_sql_query('select * from gzccnews11',con=db)

  

8. df保存到mysql数据库安装SQLALchemy安装PyMySQLMySQL里创建数据库:create database gzccnews charset utf8;

  

9、MySQL里查看已保存了数据。(通过MySQL Client或Navicate。)import pymysqlfrom sqlalchemy import create_engineconn = create_engine('mysql+pymysql://root:123456@localhost:3306/test?charset=utf8')pandas.io.sql.to_sql(df10,'gzccnews',con=conn,if_exists='replace')

  

转载于:https://www.cnblogs.com/qq1141100952com/p/8869890.html

你可能感兴趣的文章
数据结构化与保存
查看>>
C# .net 获取程序运行的路径的几种方法
查看>>
为什么需要Docker?
查看>>
国内5家云服务厂商 HTTPS 安全性测试横向对比
查看>>
how to control project
查看>>
转 python新手容易犯的6个错误
查看>>
第四节 -- 列表
查看>>
Python入门学习笔记4:他人的博客及他人的学习思路
查看>>
webstorm里直接调用命令行
查看>>
关联规则算法之FP growth算法
查看>>
对数组序列进行洗牌
查看>>
决策树
查看>>
团队作业
查看>>
如何避免在简单业务逻辑上面的细节上面出错
查看>>
win7,Ubuntu 12.04 双系统修改启动项顺序三方法
查看>>
python--列表推导式和生成表达式
查看>>
P - Psychos in a Line 单调队列
查看>>
POJ 2653 Pick-up sticks(计算几何)
查看>>
大型网站高并发的架构演变图-摘自网络
查看>>
8丶运行及总结
查看>>