python-数据结构化与保存

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).text
19   
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'))  #图1
26 
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']=url
34     news['title']=soupd.select('.show-title')[0].text
35     info=soupd.select(".show-info")[0].text
36     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'))                           #图2
42 
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/'))                                                 #图3
54 
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))   #20
69 
70 df = pandas.DataFrame(newstotal)#创建DataFrame对象
71 
72 #print(df.head()) #查看前几行的数据,默认前五行      #图4
73 #print(df['title'])                             #图5
74 #print(df[df.click>5000])#筛选
75 
76 #保存到Excel表                                    #图6
77 df.to_excel('gzccnews.xlsx')
78 
79 #保存到数据库                                      #图7
80 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、拼写和小细节错误较多,程序思路没理顺。

posted @ 2017-10-18 19:59  MayKok  阅读(2344)  评论(0编辑  收藏  举报