[娱乐] 一个监控NIKE官网NBA球衣打折的QQ机器人

上次写的微信版机器人的爬虫已经失效了,这次重新搞了爬虫,平常用的qq比较多所以也换成了qq版。

需要准备:

  • Windows服务器一台,阿里云ECS即可(Linux也可以但是需要Wine,不如直接原生Windows)
  • QQ小号一个,用来作为发送消息的载体

首先到coolq的社区下载最新版的coolq air,图灵版或者小i版都行,无所谓,我们不会用到他们的ai。

下载过后解压,双击CQA.exe即可运行coolq,之后像在电脑上登录一样登录自己的qq号即可,如下即为运行成功。

然后装一下coolq http插件,直接到release界面下载最新的插件,是一个后缀为cpk的文件,把他直接放到coolq的app目录之下

安装目录

重启coolq,之后我们还需要手动启用一下这个插件

提示需要所有权限,点确定就可以了。

这时候会弹出一个coolqHttp的cmd窗口,就说明他已经开始工作了。

之后我们来处理爬虫的问题,要做到监控nike官网的目的,首先要能实时掌握他的数据。nike的nba官网爬虫写起来还是比较简单的,只有一个坑点是他有一些球衣会放到同一个大块里,然后随机展示其中的某一项为大图,比如詹姆斯,库兹玛和戴维斯三个人就经常放到一起,然后随机詹姆斯和戴维斯两个人的球衣作为展示图。这里的处理就是在普通的json object里它有嵌套了一个object,我们只需要递归地处理一下就可以了。

# crwaler.py
import requests
import json

UA = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36'}

# 金额降序排列页面
url0 = 'https://www.nike.com/product_feed/rollup_threads/v2?filter=marketplace%28CN%29&filter=language%28zh-Hans%29&filter=employeePrice%28true%29&filter=attributeIds%281c7c3d67-5d46-432d-9910-b1128d1b6503%2Ce09eabe9-5ff0-42af-b0a3-5f68af19d89a%29&anchor=0&count=24&consumerChannelId=d9a5bc42-4b9c-4976-858a-f159cf99c647&sort=productInfo.merchPrice.currentPriceAsc'


def getObjInfo(object):
    item = {}
    item["名称"] = object["productInfo"][0]["productContent"]["title"]
    item["类型名称"] = object["productInfo"][0]["productContent"]["subtitle"]
    item["现价"] = object["productInfo"][0]["merchPrice"]["currentPrice"]
    item["原价"] = object["productInfo"][0]["merchPrice"]["fullPrice"]
    item["折扣"] = round((int(item["现价"]) / int(item["原价"])), 2)
    return item


def get_url_objcts(url=url0):
    item_list = []
    response = requests.get(url, headers=UA)
    json_dict = json.loads(response.text)
    objects = json_dict["objects"]
    for object in objects:
        item = getObjInfo(object)
        if '幼童' not in item["类型名称"]:
            item_list.append(item)
        for subObj in object["rollup"]["threads"]:
            item = getObjInfo(subObj)
            if '幼童' not in item["类型名称"]:
                item_list.append(item)

    next = json_dict["pages"]["next"]
    if next != "":
        next_url = "https://www.nike.com/" + str(next)
        item_list.extend(get_url_objcts(next_url))
    return item_list

写好爬虫之后,我们再写一个调用coolq http api的bot,实时监控有没有发生变化就可以了,这里的部分逻辑比较简单,就不多说了,关于coolq http的api可以直接看开发者的docs,讲解和demo都非常清晰明了。

import requests
import time
import copy
from crawler import *

log_file='test.log'
group_id=12345#这里填写你的qq群号,因为我是把这个bot放到一个群里通知所有人的,你也可以做你自己的,调用个人发送api。

url='http://127.0.0.1:5700'
group_path='/send_group_msg'

def send_group_msg(group_id=group_id,message=""):
    resp=requests.post(url=url+group_path,data={"group_id":group_id,"message":message}) 


ago_clothes=[]
now_clothes=[]
while(True):
    try:
        print("页面爬取开始"+str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))))
        now_clothes = get_url_objcts()
        if sorted(ago_clothes, key=lambda x: x['名称']) != sorted(now_clothes, key=lambda x: x['名称']):
            time.sleep(0.5)
            send_group_msg(message="当前时间"+str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))+"球衣数据发生变化请注意!!!!!")
            data=""
            for index, clothing in enumerate(now_clothes):
                time.sleep(0.5)
                data=data+str(clothing)+'\n\n'
                if index%3==0:
                    print(data)
                    send_group_msg(message=str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))) + '\n' + data)
                    data=''
                    print('发送成功')
            ago_clothes = now_clothes
        print("爬取完毕,等待下次执行"+str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))))
        time.sleep(300)
    except:
        print("程序出现错误,将在60秒后重试")
        time.sleep(60)
        continue

运行即可。

当然我们一个py脚本在后台很难长时间保持稳定运行下去,我们可以利用nssm把运行的python脚本作为一个Windows服务,这样就可以长期稳定运行下去了。

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据