爬取4萬多個淘寶模特信息進行數(shù)據(jù)分析

好久沒有更新博客,國慶7天,宿舍就我一個人,人生真的寂寞如雪啊。
想起我之前看過一本數(shù)據(jù)分析的書,今天想來實戰(zhàn)一下。之前由于誤刪了網(wǎng)絡(luò)爬蟲爬下來的數(shù)據(jù),所以只能重新爬取一次了,不過這次就抓取點好玩的東西,爬取淘寶淘女郎的信息來做一個簡單的數(shù)據(jù)分析。
先上爬蟲代碼:

#coding:utf-8
import requests
import os
from multiprocessing.dummy import Pool as ThreadPool
import time
from bs4 import BeautifulSoup
import urllib2,urllib
import re
class MM:
    def __init__(self):
        self.baseurl='https://mm.taobao.com/json/request_top_list.htm?page='
        self.pool = ThreadPool(10)   #初始化線程池
        self.headers={'Accept-Language':'zh-CN,zh;q=0.8','User-Agent':'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36','Connection':'close','Referer': 'https://www.baidu.com/'}
    def indexPage(self,index):
        indexpage=requests.get(self.baseurl+str(index),headers=self.headers)
        return indexpage.content.decode('GBK')

    def getAlldetail(self,index):
        indexpage=self.indexPage(index)
        p=re.compile(r'class="lady-avatar".*?<img src="(.*?)".*?class="lady-name".*?>(.*?)</a>.*?<strong>(.*?)</strong>.*?<span>(.*?)</span>',re.S)
        alldetail=re.findall(p,indexpage)
        eachdetail=[]
        for eachmm in alldetail:
            eachdetail.append(['http:'+eachmm[0],eachmm[1],eachmm[2]+'years old',eachmm[3]])
        return eachdetail

    def getImg(self,filename,imgaddr):
        f=open('mm/'+filename+'/'+filename+'.jpg','wb+')
        f.write(requests.get(imgaddr,headers=self.headers).content)
        f.close()

    def getContent(self,filename,content):     
        with open('mm/'+filename+'/'+filename+'.txt','w+') as f:
            for each in content:
                f.write((each.encode('utf-8'))+'\n')

    def mkdir(self,path):
        path = path.strip()
        isExists=os.path.exists(path)
        if not isExists:
            # 如果不存在則創(chuàng)建目錄
            print u"新建了名字叫做",path,u'的文件夾'
            # 創(chuàng)建目錄操作函數(shù)
            os.makedirs(path)
            return True                 
        else:       
            # 如果目錄存在則不創(chuàng)建,并提示目錄已存在
            print u"名為",path,'的文件夾已經(jīng)創(chuàng)建'
            return False

    def savePageInfo(self,index):
        alldetail=self.getAlldetail(index)
        for eachdetail in alldetail:
            self.mkdir('mm/'+eachdetail[1])       
            #self.mkdir('mm/')
            self.getImg(eachdetail[1],eachdetail[0])
            self.getContent(eachdetail[1],eachdetail[1:])

    def start(self):
        while 1:
            try:
                start=int(raw_input('開始查詢的頁數(shù)(整數(shù)):'))
                end=int(raw_input('結(jié)束的頁數(shù)(整數(shù)):'))
            except Exception,e:
                print e
            else:
                break
        index=range(start,end+1)
        begin=time.time()
        try:
            results = self.pool.map(self.savePageInfo,index)
            self.pool.close()
            self.pool.join()
        except Exception as e:
            print e
            pass
        end=time.time()
        total=end-begin
        print '總耗時:',total
if __name__=='__main__':
    mm=MM()
    mm.start()

運行后輸入你要爬取的頁面,就能把淘女郎的年齡,居住地,名字和照片給爬取下來。一共有4萬多個淘女郎信息,你可以全部爬取下來做數(shù)據(jù)分析用。
我只爬了幾十頁,運行后截圖:

1.png

隨便打開一個目錄,可以看到圖片和信息。
由于代碼是很久之前寫的,當時并沒有想到做數(shù)據(jù)分析,因此我對每個人都創(chuàng)建了一個目錄,每個目錄存放個人信息,這樣再單獨寫個腳本進入每個文件獲取信息效率不高,我就直接在原腳本中獲取并直接進行數(shù)據(jù)的圖像可視化,代碼如下:

#coding:utf-8
import matplotlib
import requests
import numpy as np
from matplotlib.font_manager import *
import matplotlib.pyplot as plt
import os
from multiprocessing.dummy import Pool as ThreadPool
import time
from bs4 import BeautifulSoup
import urllib2,urllib
import re
'''
#解決負號'-'顯示為方塊的問題  
matplotlib.rcParams['axes.unicode_minus']=False
'''

myfont = FontProperties(fname='/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf')
class MM:
    def __init__(self):
        self.bing={}
        self.bing1=[]
        self.zhu={}
        self.zhu1=[]
        self.baseurl='https://mm.taobao.com/json/request_top_list.htm?page='
        self.pool = ThreadPool(10)
        self.headers={'Accept-Language':'zh-CN,zh;q=0.8','User-Agent':'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36','Connection':'close','Referer': 'https://www.baidu.com/'}
    def indexPage(self,index):
        try:
            indexpage=requests.get(self.baseurl+str(index),headers=self.headers)
        except Exception as e:
            print e
        return indexpage.content.decode('GBK')

    def getAlldetail(self,index):
        indexpage=self.indexPage(index)
        p=re.compile(r'class="lady-avatar".*?<img src="(.*?)".*?class="lady-name".*?>(.*?)</a>.*?<strong>(.*?)</strong>.*?<span>(.*?)</span>',re.S)
        alldetail=re.findall(p,indexpage)
        eachdetail=[]
        for eachmm in alldetail:
            eachdetail.append(['http:'+eachmm[0],eachmm[1],eachmm[2]+'years old',eachmm[3]])
        return eachdetail

    def getImg(self,filename,imgaddr):
        #f=open('mm/'+filename+'/'+filename+'.jpg','wb+') 
        urllib.urlretrieve(imgaddr,'mm/'+filename+'/'+filename+'.jpg')
        #f.write(requests.get(imgaddr,headers=self.headers).content)
        #f.close()

    def getContent(self,filename,content):     
        with open('mm/'+filename+'/'+filename+'.txt','w+') as f:
            for each in content:
                f.write((each.encode('utf-8'))+'\n')
    
    def mkdir(self,path):
        path = path.strip()
        isExists=os.path.exists(path)
        if not isExists:
            # 如果不存在則創(chuàng)建目錄
            print u"新建了名字叫做",path,u'的文件夾'
            # 創(chuàng)建目錄操作函數(shù)
            os.makedirs(path)
            return True                 
        else:       
            # 如果目錄存在則不創(chuàng)建,并提示目錄已存在
            print u"名為",path,'的文件夾已經(jīng)創(chuàng)建'
            return False

    def savePageInfo(self,index):
        alldetail=self.getAlldetail(index) 
        for eachdetail in alldetail:
            self.mkdir('mm/'+eachdetail[1])       
            #self.mkdir('mm/')
            self.getImg(eachdetail[1],eachdetail[0])
            self.getContent(eachdetail[1],eachdetail[1:])
    def bing_pic(self,index):
        alldetail=self.getAlldetail(index)
        for eachdetail in alldetail:
            if eachdetail[3] not in self.bing:
                self.bing[eachdetail[3]]=1
            else:
                self.bing[eachdetail[3]]+=1
        
    def zhu_pic(self,index):
        alldetail=self.getAlldetail(index)
        for eachdetail in alldetail:
            eachdetail=eachdetail[2].replace('years old','')
            if eachdetail not in self.zhu:
                self.zhu[eachdetail]=1
            else:
                self.zhu[eachdetail]+=1
    def start(self):
        while 1: 
            try:
                startpage=int(raw_input('開始查詢的頁數(shù)(整數(shù)):'))
                endpage=int(raw_input('結(jié)束的頁數(shù)(整數(shù)):'))
            except Exception,e:
                print e
            else:
                break
        
        index=range(startpage,endpage+1)
        begin=time.time()
        try:
            results = self.pool.map(self.savePageInfo,index)
            self.pool.close()
            self.pool.join()
        except Exception as e:
            print e
            pass
        end=time.time()
        total=end-begin
        print '總共耗時:',total
        
        for i in range(startpage,endpage+1):
            self.zhu_pic(i)
            self.bing_pic(i)

        #柱狀圖
        for i in self.zhu:
            self.zhu1.append(self.zhu[i])
        sorted(self.zhu)
        year=[]
        for i in self.zhu:
            year.append(i)
        #print year,self.zhu1
        plt.title(u'淘女郎年齡分布圖',fontproperties=myfont,size=20)
        plt.xlabel(u'年齡',fontproperties=myfont,size=20)
        plt.ylabel(u'人數(shù)',fontproperties=myfont,size=20)
        plt.bar(year, self.zhu1)
        plt.show()

        #餅狀圖
        for i in self.bing:
            self.bing1.append(self.bing[i])
        group=[]
        for i in self.bing:
            group.append(i)
        plt.figure(num=1, figsize=(12, 12))
        plt.axes(aspect=1)
        plt.title(u'淘女郎居住地分布圖',fontproperties=myfont,size=20)
        patches,l_text,p_text=plt.pie(self.bing1,labels=group,autopct = '%3.1f%%',shadow=True, startangle=90) 
        for t in l_text: 
            t.set_fontproperties(matplotlib.font_manager.FontProperties(fname="/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf")) # 把每個文本設(shè)成中文字體
        plt.show()
if __name__=='__main__':
    mm=MM()
    mm.start()

matplotlib這個中文不能顯示這塊有點惱火,它必須要指向一個可以顯示中文的ttf文件才能顯示中文,本腳本用的matplotlib是1.5版本的,如果是其他的版本可能會出現(xiàn)因為參數(shù)的不同而出錯。

最后經(jīng)過數(shù)據(jù)分析后的圖片(以下是遍歷了1到8頁的信息后得到的圖片,你們可以繼續(xù)遍歷......)

2016-10-08 19-38-09 的屏幕截圖.png
2016-10-08 19-38-40 的屏幕截圖.png

這是數(shù)據(jù)分析的一點點皮毛,深入之后再繼續(xù)玩兒......
歡迎大牛指正.......

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容