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

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

1.结构化:

  • 单条新闻的详情字典:news
  • 一个列表页所有单条新闻汇总列表:newsls.append(news)
  • 所有列表页的所有新闻汇总列表:newstotal.extend(newsls)

2.转换成pandas的数据结构DataFrame

3.从DataFrame保存到excel

4.从DataFrame保存到sqlite3数据库

1 import requests 2 from bs4 import BeautifulSoup 3 from datetime import datetime 4 import re 5 import pandas 6 import sqlite3 7  8 url = 'http://news.gzcc.cn/html/xiaoyuanxinwen/' 9 res = requests.get(url)10 res.encoding = 'utf-8'11 soup = BeautifulSoup(res.text, 'html.parser')12 13 #给定单条新闻链接,返回点击次数14 def getclick(url):15     m=re.search(r'_(.*).html',url)16     newsid=m.group(1)[5:]17     clickurl='http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80'.format(newsid)18     resc=requests.get(clickurl).text19   20     #匹配任意位置的模式串,可以使用re.search()  #re.match()只匹配位于字符串开始位置的模式串;21     r=re.search(r'hits(.*)',resc).group(1)22     click=r.lstrip("').html('").rstrip("');")23     return int(click)24 25 #print(getclick('http://news.gzcc.cn/html/2017/xiaoyuanxinwen_1017/8338.html'))  #图126 27 #给定单条新闻链接,返回新闻细节的字典28 def getdetail(url):29     resd=requests.get(url)30     resd.encoding='utf-8'31     soupd=BeautifulSoup(resd.text,'html.parser')32     news={}33     news['url']=url34     news['title']=soupd.select('.show-title')[0].text35     info=soupd.select(".show-info")[0].text36     news['dt']=datetime.strptime(info.lstrip('发布时间:')[0:19],'%Y-%m-%d %H:%M:%S')##37     news['source']=re.search('来源:(.*)点击',info).group(1).strip()38     #news['content']=soupd.select('.show-content')[0].text.strip()39     news['click']=getclick(url)40     return(news)41 #print(getdetail('http://news.gzcc.cn/html/2017/xiaoyuanxinwen_1017/8338.html'))                           #图242 43 #给定新闻列表页的链接,返回该页所有新闻的细节字典的列表44 def onepage(pageurl):45     res=requests.get(pageurl)46     res.encoding='utf-8'47     soup=BeautifulSoup(res.text,'html.parser')48     newsls=[]49     for news in soup.select('li'):50         if len(news.select('.news-list-title'))>0:51             newsls.append(getdetail(news.select('a')[0]['href']))52     return (newsls)53 #print(onepage('http://news.gzcc.cn/html/xiaoyuanxinwen/'))                                                 #图354 55 newstotal=[]56 gzccurl='http://news.gzcc.cn/html/xiaoyuanxinwen/'57 newstotal.extend(onepage(gzccurl))58 59 res=requests.get(gzccurl)60 res.encoding='utf-8'61 soup=BeautifulSoup(res.text,'html.parser')62 n=int(soup.select('.a1')[0].text.rstrip('条'))63 pages=n//10+1 #计算多少条新闻有多少页64 65 for i in range(2,3):66     listurl='http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html'.format(i)67     newstotal.extend(onepage(listurl))#后面的每一个列表页(extend():列表1里接上列表2的内容)68 #print(len(newstotal))   #2069 70 df = pandas.DataFrame(newstotal)#创建DataFrame对象71 72 #print(df.head()) #查看前几行的数据,默认前五行      #图473 #print(df['title'])                             #图574 #print(df[df.click>5000])#筛选75 76 #保存到Excel表                                    #图677 df.to_excel('gzccnews.xlsx')78 79 #保存到数据库                                      #图780 with sqlite3.connect('gzccnews_db.sqlite') as db:81     df.to_sql('news_table',con = db)

图1:测试getclick(url)

print-1

图2:测试getdetail(url)

图3:测试onepage(pageurl)

图4:测试pandas.DataFrame(newstotal)表格数据是否创建

图5:DF数据筛选查找

图6:创建Excel表

 

图7:创建sqlite3数据库

 

 

反省:

1、忘记在每个段落方法写完后使用print()检查错误,导致要全篇检查贼累

2、拼写和小细节错误较多,程序思路没理顺。

转载于:https://www.cnblogs.com/maykok/p/7688524.html

你可能感兴趣的文章
浅谈iOS中MVVM的架构设计
查看>>
node.js 中模块的循环调用问题详解
查看>>
ActiveReports 报表应用教程 (6)---分组报表
查看>>
OLEDB操作Excel
查看>>
struts2的json-default和struts-default的区别
查看>>
java中<> 的用法
查看>>
IIS 下配置无后缀的URL ReWrite
查看>>
对Asp.net Mvc 和 jQuery UI使用者的一些忠告
查看>>
Silverlight开发历程—动画(实现跑马灯效果)
查看>>
怎么说???
查看>>
[原]Windows批处理命令学习一
查看>>
AaronYang风格 C语言挑讲[一][基本入门]
查看>>
【oneday_onepage】——The Secret Of Steve<1>
查看>>
javascript基于原型的语言的特点
查看>>
我的爱情1
查看>>
关于Cocos2d-x中地图轮播的实现
查看>>
Zookeeper运维小结--CancelledKeyException
查看>>
POJ 2104(K-th Number-区间第k大-主席树)
查看>>
HDOJ 2689
查看>>
[置顶] js综合应用:表格的四则运算
查看>>