关于python3.x:Python爬虫实战数据抓取并分析XZ销售记录数据发现了惊人的秘密

11次阅读

共计 4374 个字符,预计需要花费 11 分钟才能阅读完成。

前言

明天给大家用 Python 爬取京东的用户评估,通过数据分析实现数据可视化得出哪一种色彩的 XZ 最受女性欢送,废话不多说,间接开整~

成果展现

流程剖析

(鼠标右键或者键盘 f12)关上开发者工具 -network,在用户评估页面咱们发现浏览器有这样一个申请

通过剖析咱们发现次要用的参数有三个 productId,page,pageSize。后两个为分页参数,productId 是每个商品的 id,通过这个 id 去获取商品的评估记录,所以咱们只须要晓得每个商品的 productId 就轻而易举的获取评估了。再来剖析搜寻页面的网页源代码

通过剖析咱们发现每个商品都在 li 标签中,而 li 标签又有一个 data-pid 属性,这个对应的值就是商品的 productId 了。

网站 URL 地址获取

首先咱们须要在搜寻页面获取商品的 id,为上面爬取用户评估提供 productId。key_word 为搜寻的关键字,这里就是【XZ】

import requests
import re

"""查问商品 id"""
def find_product_id(key_word):
    jd_url = 'https://search.jd.com/Search'
    product_ids = []
    # 爬前 3 页的商品
    for i in range(1,3):
        param = {'keyword': key_word, 'enc': 'utf-8', 'page': i}
        response = requests.get(jd_url, params=param)
        # 商品 id
        ids = re.findall('data-pid="(.*?)"', response.text, re.S)
        product_ids += ids
    return product_ids

将前三页的商品 id 放入列表中,接下来咱们就能够爬取评估了

咱们通过剖析 preview 发现获取用户评估这个申请响应的格局是一个字符串前面拼接了一个 json(如下图),所以咱们只有将无用的字符删除掉,就能够获取到咱们想要的 json 对象了。

而在 json 对象中的 comments 的内容就是咱们最终想要的评估记录

"""获取评论内容"""
def get_comment_message(product_id):
    urls = ['https://sclub.jd.com/comment/productPageComments.action?' \
            'callback=fetchJSON_comment98vv53282&' \
            'productId={}' \
            '&score=0&sortType=5&' \
            'page={}' \
            '&pageSize=10&isShadowSku=0&rid=0&fold=1'.format(product_id, page) for page in range(1, 11)]
    for url in urls:
        response = requests.get(url)
        html = response.text
        # 删除无用字符
        html = html.replace('fetchJSON_comment98vv53282(', '').replace(');','')
        data = json.loads(html)
        comments = data['comments']
        t = threading.Thread(target=save_mongo, args=(comments,))
        t.start()

在这个办法中只获取了前 10 页的评估的 url,放到 urls 这个列表中。通过循环获取不同页面的评估记录,这时启动了一个线程用来将留言数据存到到 MongoDB 中。

咱们持续剖析评估记录这个接口发现咱们想要的两条数据

productColor:产品色彩

productSize:产品尺寸

# mongo 服务
client = pymongo.MongoClient('mongodb://127.0.0.1:27017/')
# jd 数据库
db = client.jd
# product 表, 没有主动创立
product_db = db.product

#  保留 mongo
def save_mongo(comments):
    for comment in comments:
        product_data = {}
        # 色彩
        # flush_data 荡涤数据的办法
        product_data['product_color'] = flush_data(comment['productColor'])
        # size
        product_data['product_size'] = flush_data(comment['productSize'])
        # 评论内容
        product_data['comment_content'] = comment['content']
        # create_time
        product_data['create_time'] = comment['creationTime']
        # 插入 mongo
        product_db.insert(product_data)

因为每种商品的色彩、尺寸形容上有差别,为了方面统计,咱们进行了简略的数据荡涤。

def flush_data(data):
    if '肤' in data:
        return '肤色'
    if '黑' in data:
        return '彩色'
    if '紫' in data:
        return '紫色'
    if '粉' in data:
        return '粉色'
    if '蓝' in data:
        return '蓝色'
    if '白' in data:
        return '红色'
    if '灰' in data:
        return '灰色'
    if '槟' in data:
        return '香槟色'
    if '琥' in data:
        return '琥珀色'
    if '红' in data:
        return '红色'
    if '紫' in data:
        return '紫色'
    if 'A' in data:
        return 'A'
    if 'B' in data:
        return 'B'
    if 'C' in data:
        return 'C'
    if 'D' in data:
        return 'D'

这几个模块的性能编写结束,上面只须要将他们分割起来

# 创立一个线程锁
lock = threading.Lock()

# 获取评论线程
def spider_jd(ids):
    while ids:
        # 加锁
        lock.acquire()
        # 取出第一个元素
        id = ids[0]
        # 将取出的元素从列表中删除,防止反复加载
        del ids[0]
        # 开释锁
        lock.release()
        # 获取评论内容
        get_comment_message(id)


product_ids = find_product_id('XZ')
for i in (1, 5):
    # 减少一个获取评论的线程
    t = threading.Thread(target=spider_jd, args=(product_ids,))
    # 启动线程
    t.start()

运行之后的查看 MongoDB:

失去后果之后,为了能更直观的体现数据,咱们能够用 matplotlib 库进行图表化展现

import pymongo
from pylab import *


client = pymongo.MongoClient('mongodb://127.0.0.1:27017/')
# jd 数据库
db = client.jd
# product 表, 没有主动创立
product_db = db.product
# 统计以下几个色彩
color_arr = ['肤色', '彩色', '紫色', '粉色', '蓝色', '红色', '灰色', '香槟色', '红色']

color_num_arr = []
for i in color_arr:
    num = product_db.count({'product_color': i})
    color_num_arr.append(num)

# 显示的色彩
color_arr = ['bisque', 'black', 'purple', 'pink', 'blue', 'white', 'gray', 'peru', 'red']

#labeldistance,文本的地位离远点有多远,1.1 指 1.1 倍半径的地位
#autopct,圆外面的文本格式,%3.1f%% 示意小数有三位,整数有一位的浮点数
#shadow,饼是否有暗影
#startangle,起始角度,0,示意从 0 开始逆时针转,为第一块。个别抉择从 90 度开始比拟难看
#pctdistance,百分比的 text 离圆心的间隔
#patches, l_texts, p_texts,为了失去饼图的返回值,p_texts 饼图外部文本的,l_texts 饼图外 label 的文本
patches,l_text,p_text = plt.pie(sizes, labels=labels, colors=colors,
                                labeldistance=1.1, autopct='%3.1f%%', shadow=False,
                                startangle=90, pctdistance=0.6)
#扭转文本的大小
#办法是把每一个 text 遍历。调用 set_size 办法设置它的属性
for t in l_text:
    t.set_size=(30)
for t in p_text:
    t.set_size=(20)
# 设置 x,y 轴刻度统一,这样饼图能力是圆的
plt.axis('equal')
plt.title("内衣色彩比例图", fontproperties="SimHei") #
plt.legend()
plt.show()

运行代码,咱们发现肤色的最受欢迎 其次是彩色

接下来咱们再来统计一下 size 的分布图,这里用柱状图进行显示

index=["A","B","C","D"]

client = pymongo.MongoClient('mongodb://127.0.0.1:27017/')
db = client.jd
product_db = db.product

value = []
for i in index:
    num = product_db.count({'product_size': i})
    value.append(num)

plt.bar(left=index, height=value, color="green", width=0.5)

plt.show()

运行后咱们发现 B size 的女性更多一些

文章到这里就完结了,感激你的观看,Python 爬虫实战系列,下篇文章分享给女朋友买礼物

为了感激读者们,我想把我最近珍藏的一些编程干货分享给大家,回馈每一个读者,心愿能帮到你们。

干货次要有:

① 2000 多本 Python 电子书(支流和经典的书籍应该都有了)

② Python 规范库材料(最全中文版)

③ 我的项目源码(四五十个乏味且经典的练手我的项目及源码)

④ Python 根底入门、爬虫、web 开发、大数据分析方面的视频(适宜小白学习)

⑤ Python 学习路线图(辞别不入流的学习)

⑥ 两天的 Python 爬虫训练营直播权限

All done~ 详见个人简介获取残缺源代码。。

正文完
 0