python抓取網頁資料處理後視覺化
阿新 • • 發佈:2018-12-06
抓取文章的連結,訪問量儲存到本地
1 #coding=utf-8 2 import requests as req 3 import re 4 import urllib 5 from bs4 import BeautifulSoup 6 import sys 7 import codecs 8 import time 9 10 11 r=req.get('https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000', 12 headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'}) 13 content=r.text 14 #print(content) 15 soup=BeautifulSoup(content,'html.parser') 16 17 #下面2行內容解決UnicodeEncodeError: 'ascii' codec can't encode characters in position 63-64問題,但是加了後print就打印不出來了,需要查原因18 reload(sys) 19 sys.setdefaultencoding('utf-8') 20 21 i=0 22 for tag in soup.find_all(re.compile(r'^a{1}'),{'class':'x-wiki-index-item'}): 23 i=i+1 24 if i%3==0: 25 time.sleep(30) 26 name=tag.get_text() 27 href='https://www.liaoxuefeng.com'+tag['href'] 28 req2=req.get(href,headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'}) 29 time.sleep(3) 30 soup2=BeautifulSoup(req2.text,'html.parser') 31 count=soup2.find_all('div',{'class':'x-wiki-info'}) 32 try: 33 co=count[0].find('span').get_text() 34 co=co[7:] 35 except IndexError as e: 36 co='0' 37 with open('E:/sg_articles.xlsx', 'a+') as f: 38 f.write(codecs.BOM_UTF8)#解決寫入csv後亂碼問題 39 f.write(name+','+href+','+co+'\n') 40 ''' 41 睡眠是因為網頁訪問過多就會報503 Service Unavailable for Bot網站超過了iis限制造成的由於2003的作業系統在提示IIS過多時並非像2000系統提示“連結人數過多” 42 http://www.51testing.com/html/53/15150753-4455790.html --資料視覺化 43 http://www.cnblogs.com/xxoome/p/5880693.html --python引入模組時import與from ... import的區別 44 https://www.cnblogs.com/amou/p/9184614.html --講解幾種爬取網頁的匹配方式 45 https://www.cnblogs.com/yinheyi/p/6043571.html --python基本語法 46 '''
上面程式碼的思路:先獲取主網頁,再遍歷主網頁上的文章連結並請求這些連結以進入子網頁,從而獲得子網頁中span標籤儲存的訪問量。
下面開啟本地檔案,pandas進行資料分析,然後pyecharts實現圖形化
1 #coding=utf-8 2 from pyecharts import Bar 3 import pandas as pd 4 5 p=pd.read_excel('E:\sg_articles.xls',names=["title","href","count"]) 6 a=p.sort_values(by='count',ascending=False)[0:3] 7 title=a['title'] 8 count=a['count'] 9 bar=Bar("點選量TOP3", title_pos='center', title_top='18', width=800, height=400) 10 bar.add("", title, count, is_convert=True, xaxis_min=10, yaxis_rotate=30, yaxis_label_textsize=10, is_yaxis_boundarygap=True, yaxis_interval=0, 11 is_label_show=True, is_legend_show=False, label_pos='right',is_yaxis_inverse=True, is_splitline_show=False) 12 bar.render("E:\點選量TOP3.html")
最後的結果
同時還有很多疑問,需要懂的朋友幫忙解答:
1.第一段程式碼中儲存的xlsx格式,實際儲存後開啟是提示有損壞的,使用xml開啟則就沒有問題,另存為xls格式後開啟也沒有問題
2.訪問量過多會報錯,我就利用了sleep,但實際上訪問量間斷性的讀取到了值,有的為什麼讀不到值了?
3.利用sort_values對count列進行排序取前3,這個會自動排除掉excel格式的第一行,不知道是為什麼
感覺後面我還需要強化1)pandas資料處理的方法,比如分組排序等
2)正則表示式的提取
3)pyecharts的圖形繪製
4)在遇到網頁有反爬情況下的虛擬ip設定等
記錄我的python學習之路,大家一起努力喲~~