Python obtain a key code to extract the network disk Baidu

The GIF graphics below are from the official website, the end of the text has given link.

description

Relying on the huge cloud Baidu network disk storage space, the number of people will get used to what the vast majority of the some of the information stored in the above, but some private links need to extract the code, but everyone wants to download private resources to remember each extraction code is clearly unrealistic. This time, cloud disk master key was born, we can obtain the appropriate link automatically eligible for the extraction code by installing the appropriate browser plug-ins. I watched a bit on Github, there is Web JSversion, pythonversion of the seemingly has not been found, so I refer the request JS version and the official website of the interface to write to get the script in two ways.

achieve

DETAILED achieve the following two methods do not explain the codes, the idea is the same, through the request interface, get data, then returns to.

V1

"""
Author:hippieZhou
Date:20190608
Description: Get BaiDuYun shared link's Code 
"""
import argparse
import re
import requests
import json
import time

VERSION = "VERSION 1.0.0"


def checkUrl(url: str) -> str:
    m1 = re.match(
        "https?:\/\/pan\.baidu\.com\/s\/1([a-zA-Z0-9_\-]{5,22})", url)
    m2 = re.match(
        "https?:\/\/pan\.baidu\.com\/share\/init\?surl=([a-zA-Z0-9_\-]{5,22})", url)
    if not m1 and not m2:
        print("参数不合法")
        return False
    else:
        return True


def getKey(url: str) -> bool:
    if checkUrl(url):
        try:
            req = requests.get(f"https://node.pnote.net/public/pan?url={url}")
            code = req.status_code
            if code == 200:
                data = dict(json.loads(req.text))
                status = data.get("status", False)
                if status:
                    return data.get("access_code", "未能查询到该链接的提取码,可能原因是:该链接不需要提取码或已过期")
                else:
                    return data.get("messages", "为能查询到提取码")
            elif code == 404:
                return "不存在该链接的记录"
        except Exception as e:
            return f"请求服务器失败,错误代码:{code}"


def get_parser():
    parser = argparse.ArgumentParser()
    parser.description = "百度网盘提取码一键获取器"
    parser.add_argument('urls', metavar="urls", type=str, nargs="*",
                        help='设置要获取提取码的链接(多个链接请用空格分隔)')
    parser.add_argument('-v', '--version', action='store_true',
                        help='版本号')
    return parser


def command_line_runner():
    parser = get_parser()
    args = vars(parser.parse_args())
    if args['version']:
        print(VERSION)
        return

    s_time = time.time()
    if len(args['urls']) > 1:
        for item in args["urls"][1:]:
            print(f"{item}:\r\n\t{getKey(item)}")
        e_time = time.time()
        print(f"\n\n操作完毕,总耗时:{e_time-s_time} 秒")


def main():
    command_line_runner()


if __name__ == "__main__":
    main()

Run results as shown below:

v2

"""
Author:hippieZhou
Date:20190608
Description: Get BaiDuYun shared link's Code 
"""

import argparse
import time
import re
import requests
from datetime import datetime
import json

accessKey = "4fxNbkKKJX2pAm3b8AEu2zT5d2MbqGbD"
clientVersion = "web-client"


def getPid(url: str) -> str:
    matches = re.match(
        "https?:\/\/pan\.baidu\.com\/s\/1([a-zA-Z0-9_\-]{5,22})", url)
    return matches[1] if matches else None


def getUuid(pid: str) -> str:
    return f"BDY-{pid}"


def getKey(url: str) -> str:
    pid = getPid(url)
    uuid = getUuid(pid)
    headers = {
        "type": "GET",
        "data": '',
        "dataType": "json"
    }
    url = f"http://ypsuperkey.meek.com.cn/api/items/{uuid}?access_key={accessKey}&client_version={clientVersion}&{datetime.utcnow()}"
    try:
        req = requests.get(url, headers=headers)
        code = req.status_code
        if code == 200:
            data = json.loads(req.text)
            accessCode = data.get("access_code", None)
            return "没找到提取密码,o(╥﹏╥)o" if (accessCode == "undefined" or accessCode == None or accessCode == "") else accessCode
        elif code == 400:
            return " 服务器不理解请求的语法"
        elif code == 404:
            return "不存在该链接的记录"
        else:
            return f"请求服务器失败,错误代码:{code}"
    except Exception as e:
        return e


def get_parser():
    parser = argparse.ArgumentParser()
    parser.description = "百度网盘提取码一键获取器"
    parser.add_argument('urls', metavar="urls", type=str, nargs="*",
                        help='设置要获取提取码的链接(多个链接请用空格分隔)')
    parser.add_argument('-v', '--version', action='store_true',
                        help='版本号')
    return parser


def command_line_runner():
    parser = get_parser()
    args = vars(parser.parse_args())
    if args['version']:
        print(VERSION)
        return

    s_time = time.time()
    if len(args['urls']) > 1:
        for item in args["urls"][1:]:
            print(f"{item}:\r\n\t{getKey(item)}")
        e_time = time.time()
        print(f"\n\n操作完毕,总耗时:{e_time-s_time} 秒")


def main():
    command_line_runner()


if __name__ == "__main__":
    main()

Run results as shown below:

to sum up

v1 and v2 version Version is achieved through different ways request interface, data interface v2 relatively more precise. Specific can be found in the specific code.

If you think the above code correctly, please visit the corresponding warehouse address: baidupankey carried out star, forkand follow.

Related reference

Guess you like

Origin www.cnblogs.com/hippieZhou/p/10990237.html