encode.py 6.6 KB
Newer Older
H
hjdhnx 已提交
1 2 3 4 5 6 7
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File  : encode.py
# Author: DaShenHan&道长-----先苦后甜,任凭晚风拂柳颜------
# Date  : 2022/8/29

import base64
H
hjdhnx 已提交
8 9
from urllib.parse import urljoin

H
hjdhnx 已提交
10
import requests
11 12
import requests.utils
from time import sleep
13
import os
H
hjdhnx 已提交
14
from utils.web import UC_UA,PC_UA
H
hjdhnx 已提交
15

16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
def getPreJs():
    base_path = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))  # 上级目
    lib_path = os.path.join(base_path, f'libs/pre.js')
    with open(lib_path,encoding='utf-8') as f:
        code = f.read()
    return code

def getCryptoJS():
    base_path = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))  # 上级目
    os.makedirs(os.path.join(base_path, f'libs'), exist_ok=True)
    lib_path = os.path.join(base_path, f'libs/crypto-hiker.js')
    # print('加密库地址:', lib_path)
    if not os.path.exists(lib_path):
        return 'undefiend'
    with open(lib_path,encoding='utf-8') as f:
        code = f.read()
    return code

34 35 36 37 38 39
def getHome(url):
    # http://www.baidu.com:9000/323
    urls = url.split('//')
    homeUrl = urls[0] + '//' + urls[1].split('/')[0]
    return homeUrl

40 41 42 43 44 45 46 47 48 49 50 51 52 53
class OcrApi:
    def __init__(self,api):
        self.api = api

    def classification(self,img):
        try:
            code = requests.post(self.api,data=img,headers={'user-agent':PC_UA}).text
        except Exception as e:
            print(f'ocr识别发生错误:{e}')
            code = ''
        return code

def verifyCode(url,headers,timeout=5,total_cnt=3,api=None):
    if not api:
54 55
        # api = 'http://192.168.3.224:9000/api/ocr_img'
        api = 'http://dm.mudery.com:10000'
56 57 58 59 60 61
    lower_keys = list(map(lambda x: x.lower(), headers.keys()))
    host = getHome(url)
    if not 'referer' in lower_keys:
        headers['Referer'] = host
    print(f'开始自动过验证,请求头:{headers}')
    cnt = 0
62
    ocr = OcrApi(api)
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
    while cnt < total_cnt:
        s = requests.session()
        try:
            img = s.get(url=f"{host}/index.php/verify/index.html", headers=headers,timeout=timeout).content
            code = ocr.classification(img)
            print(f'第{cnt+1}次验证码识别结果:{code}')
            res = s.post(
                url=f"{host}/index.php/ajax/verify_check?type=search&verify={code}",
                headers=headers).json()
            if res["msg"] == "ok":
                cookies_dict = requests.utils.dict_from_cookiejar(s.cookies)
                cookie_str = ';'.join([f'{k}={cookies_dict[k]}' for k in cookies_dict])
                # return cookies_dict
                return cookie_str
        except:
            print(f'第{cnt+1}次验证码提交失败')
            pass
        cnt += 1
        sleep(1)
    return ''

H
hjdhnx 已提交
84 85 86 87 88 89
def base64Encode(text):
    return base64.b64encode(text.encode("utf8")).decode("utf-8") #base64编码

def baseDecode(text):
    return base64.b64decode(text).decode("utf-8") #base64解码

H
hjdhnx 已提交
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
def setDetail(title:str,img:str,desc:str,content:str,tabs:list=None,lists:list=None):
    vod = {
        "vod_name": title.split('/n')[0],
        "vod_pic": img,
        "type_name": title,
        "vod_year": "",
        "vod_area": "",
        "vod_remarks": desc,
        "vod_actor": "",
        "vod_director": "",
        "vod_content": content
    }
    return vod

def urljoin2(a,b):
    a = str(a).replace("'",'').replace('"','')
    b = str(b).replace("'",'').replace('"','')
    # print(type(a),a)
    # print(type(b),b)
    ret = urljoin(a,b)
    return ret

def join(lists,string):
    """
    残废函数,没法使用
    :param lists:
    :param string:
    :return:
    """
    # FIXME
    lists1 = lists.to_list()
    string1 = str(string)
    print(type(lists1),lists1)
    print(type(string1),string1)
    try:
        ret = string1.join(lists1)
        print(ret)
        return ret
    except Exception as e:
        print(e)
        return ''

H
hjdhnx 已提交
132 133 134
def dealObj(obj=None):
    if not obj:
        obj = {}
H
hjdhnx 已提交
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
    encoding = obj.get('encoding') or 'utf-8'
    encoding = str(encoding).replace("'", "")
    # print(type(url),url)
    # headers = dict(obj.get('headers')) if obj.get('headers') else {}
    # headers = obj.get('headers').to_dict() if obj.get('headers') else {}
    headers = obj.get('headers') if obj.get('headers') else {}
    new_headers = {}
    # print(type(headers),headers)
    for i in headers:
        new_headers[str(i).replace("'", "")] = str(headers[i]).replace("'", "")
    # print(type(new_headers), new_headers)

    timeout = float(obj.get('timeout').to_int()) if obj.get('timeout') else None
    # print(type(timeout), timeout)
    body = obj.get('body') if obj.get('body') else {}
    new_body = {}
    for i in body:
        new_body[str(i).replace("'", "")] = str(body[i]).replace("'", "")
H
hjdhnx 已提交
153 154 155 156 157 158 159 160 161 162 163 164
    return {
        'encoding':encoding,
        'headers':new_headers,
        'timeout':timeout,
        'body': new_body,
    }

def base_request(url,obj,method=None):
    url = str(url).replace("'", "")
    if not method:
        method = 'get'
    # print(obj)
H
hjdhnx 已提交
165
    print(f'{method}:{url}')
H
hjdhnx 已提交
166 167 168
    try:
        # r = requests.get(url, headers=headers, params=body, timeout=timeout)
        if method.lower() == 'get':
H
hjdhnx 已提交
169
            r = requests.get(url, headers=obj['headers'], params=obj['body'], timeout=obj['timeout'])
H
hjdhnx 已提交
170
        else:
H
hjdhnx 已提交
171
            r = requests.post(url, headers=obj['headers'], data=obj['body'], timeout=obj['timeout'])
H
hjdhnx 已提交
172 173 174
        # r = requests.get(url, timeout=timeout)
        # r = requests.get(url)
        # print(encoding)
H
hjdhnx 已提交
175
        r.encoding = obj['encoding']
H
hjdhnx 已提交
176 177 178 179 180 181
        # print(f'源码:{r.text}')
        return r.text
    except Exception as e:
        print(f'{method}请求发生错误:{e}')
        return ''

H
hjdhnx 已提交
182 183 184 185
def fetch(url,obj,method=None):
    if not method:
        method = 'get'
    obj = dealObj(obj)
H
hjdhnx 已提交
186 187 188
    # print(f'{method}:{url}')
    if not obj.get('headers') or not obj['headers'].get('User-Agent'):
        obj['headers']['User-Agent'] = PC_UA
H
hjdhnx 已提交
189
    return base_request(url,obj,method)
H
hjdhnx 已提交
190 191

def post(url,obj):
H
hjdhnx 已提交
192 193 194 195 196 197 198
    obj = dealObj(obj)
    return base_request(url,obj,'post')

def request(url,obj,method=None):
    if not method:
        method = 'get'
    obj = dealObj(obj)
H
hjdhnx 已提交
199
    # print(f'{method}:{url}')
H
hjdhnx 已提交
200 201 202
    if not obj.get('headers') or not obj['headers'].get('User-Agent'):
        obj['headers']['User-Agent'] = UC_UA

H
hjdhnx 已提交
203 204 205 206 207 208 209 210 211
    return base_request(url, obj, method)

def buildUrl(url,obj=None):
    url = str(url).replace("'", "")
    if not obj:
        obj = {}
    new_obj = {}
    for i in obj:
        new_obj[str(i).replace("'", "")] = str(obj[i]).replace("'", "")
H
hjdhnx 已提交
212
    if str(url).find('?') < 0:
H
hjdhnx 已提交
213 214
        url = str(url) + '?'
    prs = '&'.join([f'{i}={obj[i]}' for i in obj])
H
hjdhnx 已提交
215 216
    if len(new_obj) > 0:
        url += '&'
H
hjdhnx 已提交
217 218 219
    url = (url + prs).replace('"','').replace("'",'')
    # print(url)
    return url