<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          爬取淘寶熱賣商品并可視化分析,看看大家都喜歡買什么

          共 9530字,需瀏覽 20分鐘

           ·

          2021-05-16 00:40



          01
          前言




          大家好,歡迎來到 Crossin的編程教室 !

          網(wǎng)上購(gòu)物早已成為當(dāng)代人生活中不可或缺的一步,除了購(gòu)買生活必需品之外,沒事“剁個(gè)手”也成為很多人解壓的一種方式。以至于現(xiàn)在幾乎每個(gè)月都被弄出一兩個(gè)“購(gòu)物節(jié)”來。

          最近突然好奇:大家在網(wǎng)上究竟都在買些啥?想到這個(gè)可以通過python來獲取淘寶上的銷量數(shù)據(jù)來進(jìn)行分析。于是有了這個(gè)想法后,剩下的就是開始動(dòng)手寫程序?qū)崿F(xiàn)這個(gè)想法啦!


          02
          采集數(shù)據(jù)



          網(wǎng)頁鏈接

          這次我們通過淘寶的“每日特賣榜單”進(jìn)行分析。這個(gè)頁面的好處是無需登錄賬號(hào)也可以獲取到數(shù)據(jù)。
          https://temai.taobao.com/



          獲取數(shù)據(jù)


          法一失敗):


          起初我采用獲取網(wǎng)頁URL地址的方式去獲取數(shù)據(jù),發(fā)現(xiàn)數(shù)據(jù)是異步加載,無法直接從請(qǐng)求URL地址獲取,所以這條路行不通!


          法二成功):


          既然是異步加載數(shù)據(jù),因此我們需要通過抓包的方式去查看異步數(shù)據(jù)包!


          這一步我們可以借助 Chrome 的開發(fā)者工具來實(shí)現(xiàn),參考之前的文章:

          爬蟲必備工具,掌握它就解決了一半的問題


          數(shù)據(jù)包鏈接


          https://h5api.m.taobao.com/h5/mtop.alimama.union.xt.en.api.entry/1.0/?jsv=2.5.1&appKey=12574478&t=1612339221271&sign=8e979106ca943a3865fca277d548b607&api=mtop.alimama.union.xt.en.api.entry&v=1.0&AntiCreep=true&type=jsonp&dataType=jsonp&callback=mtopjsonp1&data=%7B%22pNum%22%3A0%2C%22pSize%22%3A%2288%22%2C%22floorId%22%3A%2223919%22%2C%22spm%22%3A%22a2e1u.13363363.35064267%22%2C%22app_pvid%22%3A%22201_11.186.139.24_4385651_1612339221783%22%2C%22ctm%22%3A%22spm-url%3A%3Bpage_url%3Ahttps%253A%252F%252Ftemai.taobao.com%252F%22%7D




          從上圖可以看出,數(shù)據(jù)包中的數(shù)據(jù)與目標(biāo)內(nèi)容一致,因此通過python訪問這個(gè)數(shù)據(jù)包即可獲取數(shù)據(jù)!


          這里使用了 requests 庫(kù),用來做網(wǎng)絡(luò)請(qǐng)求很方便。參考文章:

          讓你的爬蟲開發(fā)效率提升8倍



          編程爬取數(shù)據(jù)


          問題1:權(quán)限問題


          如果直接放到瀏覽器訪問,會(huì)發(fā)現(xiàn)無法返回json數(shù)據(jù),根據(jù)多年的經(jīng)驗(yàn)來看,這個(gè)url鏈接的訪問有權(quán)限問題?。ㄍ碓诔绦虼a里面直接request時(shí)會(huì)出錯(cuò))


          解決方法


          在請(qǐng)求附上請(qǐng)求頭headers,即可解決這個(gè)問題!


          headers = {    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36',    'cookie':'cna=QsEFGOdo0BICARsnWHe+63/1; hng=CN%7Czh-CN%7CCNY%7C156; thw=cn; t=effdb32648fc8553a0d1a87926b80343; ctoken=M9E3xvdCNyLPC-Zyg-ZtE-nV; lego2_cna=TE08X4XP4MY5HRU8CUWMXPWD; __wpkreporterwid_=6809b44b-13ba-4faf-b370-b3788df99e39; mt=ci%3D-1_0; _m_h5_tk=843522e3dd448b136527b03c459d75b4_1612344437570; _m_h5_tk_enc=b21044b7bd07665cd105ce83fc4b4339; xlly_s=1; isg=BF1daNoy4eZf_bpk6aW7OIxsbDlXepHMvS62OB8imbTj1n0I58qhnCtEAMpQDamE; tfstk=cfNPBXYKM_CP5qGCBbGeVJ9975URwvV31T3KEJHXW-6LU4fDOH3mpNr8YcCmE; l=eBIj49hqOGMgJjg9BOfanurza77OSIRYYuPzaNbMiOCPOyfB5Hu1W6MaTD86C3GVh6XDR3yMI8QMBeYBqQAonxvOaGUhCOMmn',    'referer':'https://temai.taobao.com/',}


          這里cookie的來源于數(shù)據(jù)包,從你的網(wǎng)頁開發(fā)者工具里復(fù)制即可。(無需登錄,也建議不要登錄以免被封號(hào))



          問題2:中文亂碼



          解決方法


          如果使用 .text 屬性,可以指定編碼類型:

          r.encoding = 'utf8's = r.text


          如果使用的是 content 屬性,可以手動(dòng)解碼:

          ###亂碼問題s = r.contents = s.decode('utf8')


          請(qǐng)求數(shù)據(jù)


          import requests###請(qǐng)求urlurl="https://h5api.m.taobao.com/h5/mtop.alimama.union.xt.en.api.entry/1.0/?jsv=2.5.1&appKey=12574478&t=1612344646955&sign=9650d7c2752bc40a2bde0b90b44d58d4&api=mtop.alimama.union.xt.en.api.entry&v=1.0&AntiCreep=true&type=jsonp&dataType=jsonp&callback=mtopjsonp2&data=%7B%22pNum%22%3A0%2C%22pSize%22%3A%2288%22%2C%22floorId%22%3A%2223919%22%2C%22spm%22%3A%22a2e1u.13363363.35064267%22%2C%22app_pvid%22%3A%22201_11.186.139.24_4399690_1612344646453%22%2C%22ctm%22%3A%22spm-url%3A%3Bpage_url%3Ahttps%253A%252F%252Ftemai.taobao.com%252F%22%7D"###requests+請(qǐng)求頭headersr = requests.get(url, headers=headers)r.encoding = 'utf8's = r.texts = s.replace("mtopjsonp1(","").replace(")","")


          提取內(nèi)容


          ###轉(zhuǎn)為json格式s = json.loads(s)resultList = s['data']['recommend']['resultList']
          for i in resultList: ###商品名稱 itemName = i['itemName'] print("商品名稱="+str(itemName)) ###月銷量 monthSellCount = i['monthSellCount'] print("月銷量"+str(monthSellCount)) ###價(jià)格 priceAfterCoupon = i['priceAfterCoupon'] print("價(jià)格"+str(priceAfterCoupon)) ###原價(jià) promotionPrice = i['promotionPrice'] print("原價(jià)="+str(promotionPrice)) ###店鋪名稱 shopTitle = i['shopTitle'] print("店鋪名稱="+str(shopTitle)) ###優(yōu)惠劵總數(shù) couponTotalCount = i['couponTotalCount'] print("優(yōu)惠劵總數(shù)="+str(couponTotalCount)) ###優(yōu)惠劵領(lǐng)取數(shù) couponSendCount = i['couponSendCount'] print("優(yōu)惠劵領(lǐng)取數(shù)="+str(couponSendCount)) print("-------------------------")



          我們提取好了所需字段(商品名稱、月銷量、價(jià)格、原價(jià)、店鋪名稱、優(yōu)惠劵總數(shù)、優(yōu)惠劵領(lǐng)取數(shù))。


          接下來進(jìn)行可視化分析!



          03
          可視化分析



          分析一:月銷量排行


          ###分析1:銷量分析def analysis1(indexlist):    #商品名稱    itemNames = []    #銷量    datas = []    for j in indexlist:        ###商品名稱        itemName = resultList[new_countdict[j][0]]['itemName']        print("商品名稱=" + str(itemName)[0:10].replace(" ",""))        itemNames.append(str(itemName)[0:10].replace(" ",""))        ###月銷量        monthSellCount = resultList[new_countdict[j][0]]['monthSellCount']        print("月銷量" + str(monthSellCount))        datas.append(int(monthSellCount))
          itemNames.reverse() datas.reverse()
          # 繪圖。 fig, ax = plt.subplots() b = ax.barh(range(len(itemNames)), datas, color='#6699CC')
          # 為橫向水平的柱圖右側(cè)添加數(shù)據(jù)標(biāo)簽。 for rect in b: w = rect.get_width() ax.text(w, rect.get_y() + rect.get_height() / 2, '%d' % int(w), ha='left', va='center')
          # 設(shè)置Y軸縱坐標(biāo)上的刻度線標(biāo)簽。 ax.set_yticks(range(len(itemNames))) ax.set_yticklabels(itemNames) plt.title('淘寶商品熱賣月銷量', loc='center', fontsize='20', fontweight='bold', color='red')
          plt.show()


          分析


          1、淘寶熱賣銷量第一名:李子柒螺螄粉柳州螺獅,月銷量達(dá)到了85萬

          2、從熱賣銷量的前10名來看,螺螄粉比較受歡迎,甚至霸占了前幾名

          3、從熱賣銷量的前10名來看,用戶在網(wǎng)購(gòu)方面偏向于購(gòu)買食物


          分析二:優(yōu)惠券領(lǐng)取量分析


          ###分析2:優(yōu)惠券領(lǐng)取量分析def analysis2(indexlist):    # 商品名稱    itemNames = []    # 優(yōu)惠券總量    datas1 = []    # 優(yōu)惠券領(lǐng)取量    datas2 = []    for i in range(0,len(indexlist)):        j = indexlist[i]        ###商品名稱        itemName = resultList[new_countdict[j][0]]['itemName']        print("商品名稱=" + str(itemName)[0:10].replace(" ", ""))        itemNames.append(str(i+1)+str(itemName)[1:4].replace(" ", ""))        ###優(yōu)惠劵總數(shù)        couponTotalCount = resultList[new_countdict[j][0]]['couponTotalCount']        print("優(yōu)惠劵總數(shù)=" + str(couponTotalCount))        datas1.append(int(couponTotalCount))        ###優(yōu)惠劵領(lǐng)取數(shù)        couponSendCount = resultList[new_countdict[j][0]]['couponSendCount']        print("優(yōu)惠劵領(lǐng)取數(shù)=" + str(couponSendCount))        datas2.append(int(couponSendCount))    N = len(datas1)    S = datas1    C = datas2    d = []    for i in range(0, len(S)):        sum = S[i] + C[i]        d.append(sum)
          ind = np.arange(N) # the x locations for the groups width = 0.35 # the width of the bars: can also be len(x) sequence
          p1 = plt.bar(ind, S, width, color='#d62728') # , yerr=menStd) p2 = plt.bar(ind, C, width, bottom=S) # , yerr=womenStd) plt.ylabel('數(shù)量') plt.title('優(yōu)惠券領(lǐng)取分析') itemNames plt.xticks(ind, itemNames) plt.legend((p1[0], p2[0]), ('優(yōu)惠券總量', '優(yōu)惠券領(lǐng)取數(shù)'))
          plt.show()



          分析


          由于商品名稱名字太長(zhǎng),所以就截取前幾位!同時(shí)從1-10是按銷量從大到小順序!


          1. 從圖表上可以看出,銷量第一:李子柒螺螄粉柳州螺獅的優(yōu)惠券總量遙遙領(lǐng)先

          2. 在上面的分析可知,李子柒螺螄粉柳州螺獅的銷量最大,所以優(yōu)惠券領(lǐng)取量也隨之猛增

          3. 值得關(guān)注的是第九名:紐西之謎隔離霜妝前乳女打底水潤(rùn)提亮膚色隱形毛孔出水官方正品的優(yōu)惠券領(lǐng)取量竟然為0,看來客戶群是真土豪,都不使用優(yōu)惠券


          分析三:商品優(yōu)惠金額分析


          ###分析3:優(yōu)惠券金額分析def analysis3(indexlist):    # 商品名稱    itemNames = []    # 優(yōu)惠券金額    datas = []
          for i in range(0,len(indexlist)): j = indexlist[i] ###商品名稱 itemName = resultList[new_countdict[j][0]]['itemName'] print("商品名稱=" + str(itemName).replace(" ", "")) itemNames.append(str(i+1)+str(itemName)[0:6].replace(" ", "")) ###優(yōu)惠劵金額 couponAmount = resultList[new_countdict[j][0]]['couponAmount'] print("優(yōu)惠劵金額=" + str(couponAmount)) datas.append(int(couponAmount))
          x = range(len(itemNames)) plt.plot(x, datas, marker='o', mec='r', mfc='w', label=u'優(yōu)惠金額') plt.legend() # 讓圖例生效 plt.xticks(x, itemNames, rotation=45) plt.margins(0) plt.subplots_adjust(bottom=0.15) plt.xlabel(u"商品名稱") # X軸標(biāo)簽 plt.ylabel("金額") # Y軸標(biāo)簽 plt.title("優(yōu)惠券金額分析") # 標(biāo)題
          plt.show()



          分析


          1. 從圖表可以看出銷量第9名商品的優(yōu)惠金額最大(30元)

          2. 第7名的優(yōu)惠金額竟然為0,那可以推斷出這個(gè)商品沒有優(yōu)惠

          3. 第1、4、6、8、10,這幾個(gè)商品的優(yōu)惠金額<=5



          分析四:商品原價(jià)與限價(jià)對(duì)比分析


          ###分析4:商品原價(jià)和限價(jià)對(duì)比分析def analysis4(indexlist):    # 商品名稱    itemNames = []    # 原價(jià)    datas1 = []    # 限價(jià)    datas2 = []
          for i in range(0,len(indexlist)): j = indexlist[i] ###商品名稱 itemName = resultList[new_countdict[j][0]]['itemName'] print("商品名稱=" + str(itemName).replace(" ", "")) itemNames.append(str(i+1)+str(itemName)[1:4].replace(" ", "")) ###原價(jià) promotionPrice = resultList[new_countdict[j][0]]['promotionPrice'] print("原價(jià)=" + str(promotionPrice)) datas1.append(float(promotionPrice)) ###限價(jià) priceAfterCoupon = resultList[new_countdict[j][0]]['priceAfterCoupon'] print("價(jià)格=" + str(priceAfterCoupon)) datas2.append(float(priceAfterCoupon))
          font_size = 10 # 字體大小 fig_size = (8, 6) # 圖表大小
          names = (u'限價(jià)', u'原價(jià)') data = (datas2,datas1)
          # 更新字體大小 mpl.rcParams['font.size'] = font_size # 更新圖表大小 mpl.rcParams['figure.figsize'] = fig_size # 設(shè)置柱形圖寬度 bar_width = 0.35
          index = np.arange(len(data[0])) # 繪制「小明」的成績(jī) rects1 = plt.bar(index, data[0], bar_width, color='#0072BC', label=names[0]) # 繪制「小紅」的成績(jī) rects2 = plt.bar(index + bar_width, data[1], bar_width, color='#ED1C24', label=names[1]) # X軸標(biāo)題 plt.xticks(index + bar_width, itemNames) # Y軸范圍 plt.ylim(ymax=100, ymin=0) # 圖表標(biāo)題 plt.title(u'商品原價(jià)和限價(jià)對(duì)比分析') # 圖例顯示在圖表下方 plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.03), fancybox=True, ncol=5)
          # 添加數(shù)據(jù)標(biāo)簽 def add_labels(rects): for rect in rects: height = rect.get_height() plt.text(rect.get_x() + rect.get_width() / 2, height, height, ha='center', va='bottom') # 柱形圖邊緣用白色填充,純粹為了美觀 rect.set_edgecolor('white')
          add_labels(rects1) add_labels(rects2)
          # 圖表輸出到本地 plt.savefig('4.png')


          分析


          1. 從圖中可以看出在這前10大銷量商品中,價(jià)格最高是第9(紐西之謎隔離霜妝前乳),其次是第5(拖把免手洗家用干濕兩用拖布),價(jià)格最低的是第6(酸辣無骨雞爪)

          2. 從原價(jià)和限價(jià)對(duì)比來看,差值最大的是第9(紐西之謎隔離霜妝前乳)


          04
          總結(jié)



          1. 詳細(xì)介紹了數(shù)據(jù)的爬取過程,可方便新手學(xué)習(xí)入門學(xué)習(xí)

          2. 通過不同的可視化圖表對(duì)數(shù)據(jù)進(jìn)行展示

          3. 對(duì)可視化圖表進(jìn)行精簡(jiǎn)總結(jié)歸納,便于理解

          4. 代碼很詳細(xì)!


          獲取代碼請(qǐng)?jiān)诠娞?hào)里回復(fù)關(guān)鍵字: 淘寶


          如果文章對(duì)你有幫助,歡迎轉(zhuǎn)發(fā)/點(diǎn)贊/收藏~

          作者:李運(yùn)辰

          來源:Python研究者


          _往期文章推薦_

          Python模擬登錄淘寶




          如需了解付費(fèi)精品課程教學(xué)答疑服務(wù)
          請(qǐng)?jiān)?strong style="max-width: 100%;overflow-wrap: break-word !important;box-sizing: border-box !important;">Crossin的編程教室內(nèi)回復(fù): 666

          瀏覽 36
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  成人高清无码视频在线免费观看 | 蜜桃网址一区在线观看 | 一区免费在线 | 白丝暴肛在线观看91 | 青青免费在线观看高清无码视频 |