7

姐姐想在淘宝开个店,我用Python做了一波市场分析,居然发现生财之道!

 2 years ago
source link: https://blog.csdn.net/weixin_48294073/article/details/119611083
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

几个月前,姐姐跟我说要在淘宝上开一个网店,把家里池塘养的鱼做成零食去卖,因为网上有很多这种小鱼零食网店,看起来销量都还不错。

请添加图片描述

姐姐知道我会一些在她们眼里比较“高超的技术”,所以就问我能不能帮她弄一些这方面的数据,因为在开店之前得做一些调查,比如说哪些价位的小鱼零食卖得最多这种调查。当然了,自己也可以手动去统计,但那很麻烦并容易出错,所以用技术来解决最为合适。

这对我来说倒不是什么很难的事情,于是抽空就给她去做了一波爬虫和数据分析,最后把数据结果给了她,经过她一分析之后,发现原来看似红海的小鱼零食市场,居然还有蓝海区域,在一番准备之后,姐姐就开始经营她的小鱼零食店铺,第一个月的除去成本和广告等支出,居然赚了3万多!

接下来,我给大家分享一下我是怎么用Python去给姐姐做的淘宝店铺市场调查。


一、项目需求

首先,我要爬取的目标网址自然是淘宝了,目标网址:

https://s.taobao.com/search?q=%E5%B0%8F%E9%B1%BC%E9%9B%B6%E9%A3%9F&imgfile=&commend=all&ssid=s5-e&search_type=item&sourceId=tb.index&spm=a21bo.21814703.201856-taobao-item.1&ie=utf8&initiative_id=tbindexz_20170306&bcoffset=4&ntoffset=4&p4ppushleft=2%2C48&s=0

然后我们来看一下姐姐的需求是有哪些:

1.爬取前10页淘宝商品的销量和金额,找出各价位商品销量,并用图形展示分析结果,价位按以下10个区间分:
在这里插入图片描述

2.爬取前10页淘宝商家的地理位置信息,并用图形展示分析结果。

3.爬取前10页中购买人数最多的10家店名和对于的小鱼零食链接(1家店1个链接即可)。

4.爬取购买人数最多的10家店铺中已购买的用户评论关键词,生成词图。

从上面这4个需求来看,很明显姐姐想要知道现在的小鱼零食市场店铺最多的是哪些价位、这些店铺在哪些区域、做得比较好的店铺有哪些以及用户最关心的是什么。


二、效果预览

代码我写了差不多2天的时间,基本上已经把姐姐的需求全部弄出来了,我们来看看效果。

1.淘宝前10页的所有小鱼零食产品,在不同价位区间的数量情况。

在这里插入图片描述
可以看出来,在10~30块钱的价位上,小鱼零食已经是一片红海了,卖的人太多,基本没得赚,其次是低于10块钱和30—50元这两个区间,卖的也很多;比较有意思的是70到90元这个区间,只有5家,110到130这个区间,只有1家。

那么可以考虑一下做中高端的市场,这里还是一片蓝海。

2.全国卖小鱼零食的店铺区域分布图

在这里插入图片描述
姐姐家是在湖南,得益于洞庭湖水系的滋养,在网上卖小鱼零食的商家还是有不少的,其次便是沿海一带最为多,看来姐姐在生意上的竞争对手就在身边。

3.购买人数最多的10家店铺链接

在这里插入图片描述
有了这个,姐姐就可以自己去经常参考别人是怎么做的了,其实这个在淘宝上也能勾选出来销量最多的产品,我不是很理解为什么要这么做,但还是做了。

四、用户云词图

在这里插入图片描述
云词图我也只是做了一个比较粗糙的词图,我们可以看得出来,用户最关心的点就在包装品质、口感味道、保质期、商品分量等方面,在了解了用户最关心的点之后,产品的设计、店铺搭建、广告词等等东西就可以“对症下药”了。


三、部分源码

由于源码比较长,源文件有三个,所以这里我就只展示部分源码了,需要源码的可以找我,你们也可以自己去做一些别的品类的淘宝产品市场分析,没准你们也能发现更多的生财之道!

部分源码:

import csv
import os
import time
import wordcloud
from selenium import webdriver
from selenium.webdriver.common.by import By


def tongji():
    prices = []
    with open('前十页销量和金额.csv', 'r', encoding='utf-8', newline='') as f:
        fieldnames = ['价格', '销量', '店铺位置']
        reader = csv.DictReader(f, fieldnames=fieldnames)
        for index, i in enumerate(reader):
            if index != 0:
                price = float(i['价格'].replace('¥', ''))
                prices.append(price)
    DATAS = {'<10': 0, '10~30': 0, '30~50': 0,
             '50~70': 0, '70~90': 0, '90~110': 0,
             '110~130': 0, '130~150': 0, '150~170': 0, '170~200': 0, }
    for price in prices:
        if price < 10:
            DATAS['<10'] += 1
        elif 10 <= price < 30:
            DATAS['10~30'] += 1
        elif 30 <= price < 50:
            DATAS['30~50'] += 1
        elif 50 <= price < 70:
            DATAS['50~70'] += 1
        elif 70 <= price < 90:
            DATAS['70~90'] += 1
        elif 90 <= price < 110:
            DATAS['90~110'] += 1
        elif 110 <= price < 130:
            DATAS['110~130'] += 1
        elif 130 <= price < 150:
            DATAS['130~150'] += 1
        elif 150 <= price < 170:
            DATAS['150~170'] += 1
        elif 170 <= price < 200:
            DATAS['170~200'] += 1

    for k, v in DATAS.items():
        print(k, ':', v)


def get_the_top_10(url):
    top_ten = []
    # 获取代理
    ip = zhima1()[2][random.randint(0, 399)]
    # 运行quicker动作(可以不用管)
    os.system('"C:\Program Files\Quicker\QuickerStarter.exe" runaction:5e3abcd2-9271-47b6-8eaf-3e7c8f4935d8')
    options = webdriver.ChromeOptions()
    # 远程调试Chrome
    options.add_experimental_option('debuggerAddress', '127.0.0.1:9222')
    options.add_argument(f'--proxy-server={ip}')
    driver = webdriver.Chrome(options=options)
    # 隐式等待
    driver.implicitly_wait(3)
    # 打开网页
    driver.get(url)
    # 点击部分文字包含'销量'的网页元素
    driver.find_element(By.PARTIAL_LINK_TEXT, '销量').click()
    time.sleep(1)
    # 页面滑动到最下方
    driver.execute_script('window.scrollTo(0,document.body.scrollHeight)')
    time.sleep(1)
    # 查找元素
    element = driver.find_element(By.ID, 'mainsrp-itemlist').find_element(By.XPATH, './/div[@class="items"]')
    items = element.find_elements(By.XPATH, './/div[@data-category="auctions"]')
    for index, item in enumerate(items):
        if index == 10:
            break
        # 查找元素
        price = item.find_element(By.XPATH, './div[2]/div[1]/div[contains(@class,"price")]').text
        paid_num_data = item.find_element(By.XPATH, './div[2]/div[1]/div[@class="deal-cnt"]').text
        store_location = item.find_element(By.XPATH, './div[2]/div[3]/div[@class="location"]').text
        store_href = item.find_element(By.XPATH, './div[2]/div[@class="row row-2 title"]/a').get_attribute(
            'href').strip()
        # 将数据添加到字典
        top_ten.append(
            {'价格': price,
             '销量': paid_num_data,
             '店铺位置': store_location,
             '店铺链接': store_href
             })

    for i in top_ten:
        print(i)


def get_top_10_comments(url):
    with open('排名前十评价.txt', 'w+', encoding='utf-8') as f:
        pass
    # ip = ipidea()[1]
    os.system('"C:\Program Files\Quicker\QuickerStarter.exe" runaction:5e3abcd2-9271-47b6-8eaf-3e7c8f4935d8')
    options = webdriver.ChromeOptions()
    options.add_experimental_option('debuggerAddress', '127.0.0.1:9222')
    # options.add_argument(f'--proxy-server={ip}')
    driver = webdriver.Chrome(options=options)
    driver.implicitly_wait(3)
    driver.get(url)
    driver.find_element(By.PARTIAL_LINK_TEXT, '销量').click()
    time.sleep(1)
    element = driver.find_element(By.ID, 'mainsrp-itemlist').find_element(By.XPATH, './/div[@class="items"]')
    items = element.find_elements(By.XPATH, './/div[@data-category="auctions"]')
    original_handle = driver.current_window_handle
    item_hrefs = []
    # 先获取前十的链接
    for index, item in enumerate(items):
        if index == 10:
            break
        item_hrefs.append(
            item.find_element(By.XPATH, './/div[2]/div[@class="row row-2 title"]/a').get_attribute('href').strip())
    # 爬取前十每个商品评价
    for item_href in item_hrefs:
        # 打开新标签
        # item_href = 'https://item.taobao.com/item.htm?id=523351391646&ns=1&abbucket=11#detail'
        driver.execute_script(f'window.open("{item_href}")')
        # 切换过去
        handles = driver.window_handles
        driver.switch_to.window(handles[-1])

        # 页面向下滑动一部分,直到让评价那两个字显示出来
        try:
            driver.find_element(By.PARTIAL_LINK_TEXT, '评价').click()
        except Exception as e1:
            try:
                x = driver.find_element(By.PARTIAL_LINK_TEXT, '评价').location_once_scrolled_into_view
                driver.find_element(By.PARTIAL_LINK_TEXT, '评价').click()
            except Exception as e2:
                try:
                    # 先向下滑动100,放置评价2个字没显示在屏幕内
                    driver.execute_script('var q=document.documentElement.scrollTop=100')
                    x = driver.find_element(By.PARTIAL_LINK_TEXT, '评价').location_once_scrolled_into_view
                except Exception as e3:
                    driver.find_element(By.XPATH, '/html/body/div[6]/div/div[3]/div[2]/div/div[2]/ul/li[2]/a').click()
        time.sleep(1)
        try:
            trs = driver.find_elements(By.XPATH, '//div[@class="rate-grid"]/table/tbody/tr')
            for index, tr in enumerate(trs):
                if index == 0:
                    comments = tr.find_element(By.XPATH, './td[1]/div[1]/div/div').text.strip()
                else:
                    try:
                        comments = tr.find_element(By.XPATH,
                                                   './td[1]/div[1]/div[@class="tm-rate-fulltxt"]').text.strip()
                    except Exception as e:
                        comments = tr.find_element(By.XPATH,
                                                   './td[1]/div[1]/div[@class="tm-rate-content"]/div[@class="tm-rate-fulltxt"]').text.strip()
                with open('排名前十评价.txt', 'a+', encoding='utf-8') as f:
                    f.write(comments + '\n')
                    print(comments)
        except Exception as e:
            lis = driver.find_elements(By.XPATH, '//div[@class="J_KgRate_MainReviews"]/div[@class="tb-revbd"]/ul/li')
            for li in lis:
                comments = li.find_element(By.XPATH, './div[2]/div/div[1]').text.strip()
                with open('排名前十评价.txt', 'a+', encoding='utf-8') as f:
                    f.write(comments + '\n')
                    print(comments)


def get_top_10_comments_wordcloud():
    file = '排名前十评价.txt'
    f = open(file, encoding='utf-8')
    txt = f.read()
    f.close()

    w = wordcloud.WordCloud(width=1000,
                            height=700,
                            background_color='white',
                            font_path='msyh.ttc')
    # 创建词云对象,并设置生成图片的属性

    w.generate(txt)
    name = file.replace('.txt', '')
    w.to_file(name + '词云.png')
    os.startfile(name + '词云.png')


def get_10_pages_datas():
    with open('前十页销量和金额.csv', 'w+', encoding='utf-8', newline='') as f:
        f.write('\ufeff')
        fieldnames = ['价格', '销量', '店铺位置']
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()
    infos = []
    options = webdriver.ChromeOptions()
    options.add_experimental_option('debuggerAddress', '127.0.0.1:9222')
    # options.add_argument(f'--proxy-server={ip}')
    driver = webdriver.Chrome(options=options)
    driver.implicitly_wait(3)
    driver.get(url)
    # driver.execute_script('window.scrollTo(0,document.body.scrollHeight)')
    element = driver.find_element(By.ID, 'mainsrp-itemlist').find_element(By.XPATH, './/div[@class="items"]')
    items = element.find_elements(By.XPATH, './/div[@data-category="auctions"]')
    for index, item in enumerate(items):
        price = item.find_element(By.XPATH, './div[2]/div[1]/div[contains(@class,"price")]').text
        paid_num_data = item.find_element(By.XPATH, './div[2]/div[1]/div[@class="deal-cnt"]').text
        store_location = item.find_element(By.XPATH, './div[2]/div[3]/div[@class="location"]').text
        infos.append(
            {'价格': price,
             '销量': paid_num_data,
             '店铺位置': store_location})
    try:
        driver.find_element(By.PARTIAL_LINK_TEXT, '下一').click()
    except Exception as e:
        driver.execute_script('window.scrollTo(0,document.body.scrollHeight)')
        driver.find_element(By.PARTIAL_LINK_TEXT, '下一').click()
    for i in range(9):
        time.sleep(1)
        driver.execute_script('window.scrollTo(0,document.body.scrollHeight)')
        element = driver.find_element(By.ID, 'mainsrp-itemlist').find_element(By.XPATH, './/div[@class="items"]')
        items = element.find_elements(By.XPATH, './/div[@data-category="auctions"]')
        for index, item in enumerate(items):
            try:
                price = item.find_element(By.XPATH, './div[2]/div[1]/div[contains(@class,"price")]').text
            except Exception:
                time.sleep(1)
                driver.execute_script('window.scrollTo(0,document.body.scrollHeight)')
                price = item.find_element(By.XPATH, './div[2]/div[1]/div[contains(@class,"price")]').text
            paid_num_data = item.find_element(By.XPATH, './div[2]/div[1]/div[@class="deal-cnt"]').text
            store_location = item.find_element(By.XPATH, './div[2]/div[3]/div[@class="location"]').text
            infos.append(
                {'价格': price,
                 '销量': paid_num_data,
                 '店铺位置': store_location})
        try:
            driver.find_element(By.PARTIAL_LINK_TEXT, '下一').click()
        except Exception as e:
            driver.execute_script('window.scrollTo(0,document.body.scrollHeight)')
            driver.find_element(By.PARTIAL_LINK_TEXT, '下一').click()
        # 一页结束
        for info in infos:
            print(info)
        with open('前十页销量和金额.csv', 'a+', encoding='utf-8', newline='') as f:
            fieldnames = ['价格', '销量', '店铺位置']
            writer = csv.DictWriter(f, fieldnames=fieldnames)
            for info in infos:
                writer.writerow(info)


if __name__ == '__main__':
    url = 'https://s.taobao.com/search?q=%E5%B0%8F%E9%B1%BC%E9%9B%B6%E9%A3%9F&imgfile=&commend=all&ssid=s5-e&search_type=item&sourceId=tb.index&spm=a21bo.21814703.201856-taobao-item.1&ie=utf8&initiative_id=tbindexz_20170306&bcoffset=4&ntoffset=4&p4ppushleft=2%2C48&s=0'
    # get_10_pages_datas()
    # tongji()
    # get_the_top_10(url)
    # get_top_10_comments(url)
    get_top_10_comments_wordcloud()

四、我的姐姐

大家是不是很好奇我的姐姐长什么样子?很抱歉哈,不能给大家看脸,只能给大家看一下姐姐的背影:

在这里插入图片描述

那么今天的分享就到这里了,记得给我三连哈!

在这里插入图片描述


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK