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、拼寫和小細節錯誤較多,程序思路沒理順。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM