爬取淘寶熱賣商品并可視化分析,看看大家都喜歡買什么
https://temai.taobao.com/
法一(失敗):
起初我采用獲取網(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)求很方便。參考文章:
問題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)行可視化分析!
###分析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)買食物
###分析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 = datas1C = datas2d = []for i in range(0, len(S)):sum = S[i] + C[i]d.append(sum)ind = np.arange(N) # the x locations for the groupswidth = 0.35 # the width of the bars: can also be len(x) sequencep1 = 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)取分析')itemNamesplt.xticks(ind, itemNames)plt.legend((p1[0], p2[0]), ('優(yōu)惠券總量', '優(yōu)惠券領(lǐng)取數(shù)'))plt.show()
分析
由于商品名稱名字太長(zhǎng),所以就截取前幾位!同時(shí)從1-10是按銷量從大到小順序!
從圖表上可以看出,銷量第一:李子柒螺螄粉柳州螺獅的優(yōu)惠券總量遙遙領(lǐng)先
在上面的分析可知,李子柒螺螄粉柳州螺獅的銷量最大,所以優(yōu)惠券領(lǐng)取量也隨之猛增
值得關(guān)注的是第九名:紐西之謎隔離霜妝前乳女打底水潤(rùn)提亮膚色隱形毛孔出水官方正品的優(yōu)惠券領(lǐng)取量竟然為0,看來客戶群是真土豪,都不使用優(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()

分析
從圖表可以看出銷量第9名商品的優(yōu)惠金額最大(30元)
第7名的優(yōu)惠金額竟然為0,那可以推斷出這個(gè)商品沒有優(yōu)惠
第1、4、6、8、10,這幾個(gè)商品的優(yōu)惠金額<=5元
###分析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.35index = 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')

分析
從圖中可以看出在這前10大銷量商品中,價(jià)格最高是第9(紐西之謎隔離霜妝前乳),其次是第5(拖把免手洗家用干濕兩用拖布),價(jià)格最低的是第6(酸辣無骨雞爪)
從原價(jià)和限價(jià)對(duì)比來看,差值最大的是第9(紐西之謎隔離霜妝前乳)
詳細(xì)介紹了數(shù)據(jù)的爬取過程,可方便新手學(xué)習(xí)入門學(xué)習(xí)
通過不同的可視化圖表對(duì)數(shù)據(jù)進(jìn)行展示
對(duì)可視化圖表進(jìn)行精簡(jiǎn)總結(jié)歸納,便于理解
代碼很詳細(xì)!
獲取代碼請(qǐng)?jiān)诠娞?hào)里回復(fù)關(guān)鍵字: 淘寶
如果文章對(duì)你有幫助,歡迎轉(zhuǎn)發(fā)/點(diǎn)贊/收藏~
作者:李運(yùn)辰
_往期文章推薦_
