栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python爬虫系列之某了么h5签名sign算法

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python爬虫系列之某了么h5签名sign算法

Python爬虫系列之某了么h5签名sign算法

为维护网络绿色健康发展,相关加密已隐藏,代码仅供学习交流,请勿用于非法用途,如有侵权,请点击这里联系删除

直接上代码
# -*- coding:utf-8 -*-
import os
import requests
import configparser
import time
import json
import hashlib
import logging
import MySQLdb
from urllib.parse import urlencode
import re

pc = 'ele'
logging.basicConfig(level=logging.INFO, format='%(asctime)s - [line:%(lineno)d] - %(levelname)s: %(message)s')
cf = configparser.ConfigParser()
try:
    cf.read(os.getcwd() + "/conf.ini", encoding="utf-8-sig")
except Exception as e:
    print("程序目录下不存在conf.ini配置文件~")
    exit(0)


def getConf(sec, key):
    try:
        return cf.get(sec, key)
    except Exception as e:
        print(e)
        print("未得到以下配置:" + sec + " - " + key)
        exit(0)


host = getConf("Mysql-Database", "host")
password = getConf("Mysql-Database", "password")
port = int(getConf("Mysql-Database", "port"))
database = getConf("Mysql-Database", "database")
orderInterval = 10
try:
    orderInterval = int(getConf("app-sys", "orderInterval"))
    if orderInterval < 0:
        orderInterval = 10
except Exception as e:
    orderInterval = 10
reqInterval = 5
try:
    reqInterval = int(getConf("app-sys", "reqInterval"))
    if reqInterval < 0:
        reqInterval = 5
except Exception as e:
    reqInterval = 5
retry = 3
try:
    retry = int(getConf("app-sys", "retry"))
    if retry < 0:
        retry = 3
except Exception as e:
    retry = 3
orderPageNum = 10
try:
    orderPageNum = int(getConf("app-sys", "orderPageNum"))
    if orderPageNum < 1:
        orderPageNum = 10
except Exception as e:
    orderPageNum = 10


appKey = ""
js = '''
'''

def querySql(sql):
    try:
        conn = MySQLdb.connect(host=host, user=user, password=password, port=port, database=database, charset='utf8')
        cur = conn.cursor()
        cur.execute(sql)
        return cur.fetchall()
    except Exception as e:
        pass
    return


def getContentId(uid, ctype):
    try:
        sql = "select id from `content` where uid = '%d' and ctype = '%s'" % (int(uid), ctype)
        return querySql(sql)[0][0]
    except Exception as e:
        pass


def updateContent(id, content):
    try:
        sql = "update `content` set content = '%s' where id = %d" % (content, int(id))
        execSql(sql)
    except Exception as e:
        pass


def updateUserStatus(id, status):
    try:
        sql = "update `user` set login_status = '%s' where id = '%d' and `type` = '%s'" % (status, int(id), pc)
        return execSql(sql)
    except Exception as e:
        pass
    return False


def checkUserExists(phone):
    try:
        sql = "select * from `user` where `type` = '%s' and phone = '%s'" % (pc, str(phone))
        res = querySql(sql)
        return len(res) > 0
    except Exception as e:
        pass
    return False



def getHtml(url, headers):
    for i in range(retry):
        try:
            resp = requests.get(url, headers=headers, timeout=timeout)
            return resp.json()
        except Exception as e:
            pass


def postHtml(url, data, headers):
    for i in range(retry):
        try:
            resp = requests.post(url, data=data, headers=headers, timeout=timeout)
            return resp.json()
        except Exception as e:
            pass


def getMd5(s):
    m = hashlib.md5()
    m.update(s.encode("utf-8"))
    return m.hexdigest()


def getSign(t, data):
    return getMd5(*******)


def getReceiveAddr(headers, uid):
    t = str(time.time()).replace(".", "")[: 13]
    data = ''''''
    sign = getSign(t, data)
    url = "https://waimai-guide.ele.me/h5/mtop.alsc.personal.address.query/1.0/?jsv=2.6.2&appKey=" + str(appKey) + "&t=" + str(t) + "&sign=" + sign + "&api=mtop.alsc.personal.address.query&v=1.0&dataType=json&subDomain=waimai-guide&mainDomain=ele.me&H5Request=true&pageDomain=ele.me&needLogin=true&ttid=h5%40Web_iphone_10.6.8&type=originaljson"
    res = getHtml(url, headers)
    try:
        addrListData = []
        addressList = res['data']['addressList']
        for address in addressList:
            try:
                data = {}
                addressStr = address['address']
                try:
                    addressStr += " " + address['address_detail']
                except Exception as e:
                    pass
                data['address'] = addressStr
                data['name'] = address['name']
                data['mobile'] = address['phone']
                data['label'] = "" if address['tag'] == "未选择" else address['tag']
                addrListData.append(data)
            except Exception as e:
                pass
    except Exception as e:
        pass
    return False


def getOrderList(headers, fromTime):
    t = str(time.time()).replace(".", "")[: 13]
    data = ''''''
    sign = getSign(t, data)
    url = "https://waimai-guide.ele.me/h5/mtop.alsc.personal.queryorderlist/1.0/?jsv=2.6.1&appKey=" + str(appKey) + "&t=" + str(t) + "&sign=" + sign + "&api=mtop.alsc.personal.queryOrderList&v=1.0&type=originaljson&dataType=json&timeout=20000&subDomain=waimai-guide&mainDomain=ele.me&H5Request=true&pageDomain=ele.me&needLogin=true&ttid=h5%40Web_iphone_10.6.8"
    res = getHtml(url, headers)
    try:
        fromTime = None
        try:
            fromTime = int(res['data']['result']['moreInfo']['moreInfoParams']['fromTime'])
        except Exception as e:
            pass
        return res['data']['result']['orderList'], fromTime
    except Exception as e:
        pass
    return None, None


def getOrderDetail(taobaoId, headers):
    theaders = headers
    theaders['content-type'] = "application/x-www-form-urlencoded"
    t = str(time.time()).replace(".", "")[: 13]
    data = ''''''
    sign = getSign(t, data)
    url = "https://alsc-buy2.ele.me/h5/mtop.alsc.eleme.order.detail.miniapp.build/1.0/?jsv=2.6.2&appKey=" + str(appKey) + "&t=" + str(t) + "&sign=" + sign + "&api=mtop.alsc.eleme.order.detail.miniapp.build&v=1.0&type=originaljson&dataType=json&timeout=15000&subDomain=alsc-buy2&mainDomain=ele.me&H5Request=true&pageDomain=ele.me&needLogin=true&ttid=h5%40safari_ios_604.1"
    res = postHtml(url, data, theaders)
    try:
        data = {}
        data['receive_info'] = res['data']['order_detail_base_info']['receiving_info']['consignee']
        try:
            data['address'] = res['data']['order_detail_base_info']['receiving_info']['address']
        except Exception as e:
            data['address'] = ""
        try:
            orderShopNameList = []
            shopList = res['data']['order_detail_food']['group']
            for shop in shopList:
                try:
                    orderShopNameList.append(shop['name'])
                except Exception as e:
                    pass
            data['goods_names'] = "rn".join(orderShopNameList)
        except Exception as e:
            data['goods_names'] = ""
        try:
            data['order_status'] = res['data']['order_detail_map']['timeline']['title']
        except Exception as e:
            data['order_status'] = ""
        return data
    except Exception as e:
        pass


def getOrder(headers, uid):
    data = []
    fromTime = 0
    for i in range(orderPageNum):
        try:
            orderList, fromTime = getOrderList(headers, fromTime)
            if orderList and isinstance(orderList, list) and len(orderList) > 0:
                for i, order in enumerate(orderList):
                    try:
                        orderData = getOrderDetail("*****", headers)
                        if orderData and len(orderData) > 0:
                            data.append(orderData)
                        time.sleep(orderInterval)
                    except Exception as e:
                        time.sleep(orderInterval)
            else:
                break
            if fromTime is None:
                break
        except Exception as e:
            pass
    id = getContentId(uid, "CT3")
    if data and len(data) > 0:
        logging.info(f"CT3 - {str(data)}")
        if id is not None:
            updateContent(id, json.dumps(data, ensure_ascii=False).replace("'", "\'"))
        else:
            addContent(uid, "CT3", json.dumps(data, ensure_ascii=False).replace("'", "\'"))


def getUserInfo(headers, uid):
    t = str(time.time()).replace(".", "")[: 13]
    data = ''''''
    sign = getSign(t, data)
    url = "https://waimai-guide.ele.me/h5/mtop.alsc.personal.queryminecenter/1.0/?jsv=2.6.2&appKey=" + str(appKey) + "&t=" + str(t) + "&sign=" + sign + "&api=mtop.alsc.personal.queryMineCenter&v=1.0&dataType=json&subDomain=waimai-guide&mainDomain=ele.me&H5Request=true&pageDomain=ele.me&ttid=h5%40Web_iphone_10.6.8&type=originaljson"
    res = getHtml(url, headers)
    try:
        data = {}
        fields = res['data']['data']['h5_personal_user_information']['fields']
        data['displayedNickname'] = fields['displayedNickname']
        try:
            data['userName'] = fields['userName']
        except Exception as e:
            data['userName'] = ""
        try:
            data['mobile'] = fields['mobile']
        except Exception as e:
            data['mobile'] = ""
        logging.info(f"CT1 - {str(data)}")
        id = getContentId(uid, "CT1")
        if id is not None:
            updateContent(id, json.dumps(data, ensure_ascii=False).replace("'", "\'"))
        else:
            addContent(uid, "CT1", json.dumps(data, ensure_ascii=False).replace("'", "\'"))
        return True
    except Exception as e:
        pass
    return False


def submiter(jsonData):
    cookie = jsonData['cookie']
    phone = jsonData['phone']
    uid = selectUserByPhone(phone)
    if uid is not None:
        upStatus = updateUserLogin(phone)
        if not upStatus:
            return
    else:
        addStatus = addUser(phone)
        if not addStatus:
            return
    uid = selectUserByPhone(phone)
    headers = {
        "accept": "application/json",
        "accept-encoding": "gzip, deflate, br",
        "accept-language": "zh-CN,zh;q=0.9",
        "cache-control": "no-cache",
        "content-type": "application/x-www-form-urlencoded",
        "cookie": cookie,
        "origin": "https://h5.ele.me",
        "pragma": "no-cache",
        "referer": "*****",
        "user-agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",
        "x-ele-ua": "******",
    }
    if getUserInfo(headers, uid):
        if getReceiveAddr(headers, uid):
            getOrder(headers, uid)
            updateUserStatus(uid, "finish")
        else:
            updateUserStatus(uid, "logout")
    else:
        updateUserStatus(uid, "logout")


if __name__ == '__main__':
    headers = {
        "content-type": "application/x-www-form-urlencoded",
        "cookie": "*********",
        "origin": "https://h5.ele.me",
        "pragma": "no-cache",
        "referer": "*********",
        "user-agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",
        "x-decode-ua": "true",
        "x-ele-ua": "*********",
        "x-ua": "*********",
    }
    getOrderDetail("*********", "*********", headers)


技术交流微信:walei5201314
QQ:804682557

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1004503.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号