在Python中运行js为什么会报错?

在Python中运行js报错,在js和Python中都打印过相关类型和值了,都没问题,这是怎么回事啊?
报错和异常为:
image.png

import requests
import execjs
import sys
import io

# 设置默认编码为utf-8
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

cookies = {
    'sajssdk_2015_cross_new_user': '1',
    'sensorsdata2015jssdkcross': '%7B%22distinct_id%22%3A%2219024c17c022c2-0219b491cdda7ee-4c657b58-1327104-19024c17c038c1%22%2C%22first_id%22%3A%22%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E8%87%AA%E7%84%B6%E6%90%9C%E7%B4%A2%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC%22%2C%22%24latest_referrer%22%3A%22https%3A%2F%2Fwww.baidu.com%2Flink%22%7D%2C%22identities%22%3A%22eyIkaWRlbnRpdHlfY29va2llX2lkIjoiMTkwMjRjMTdjMDIyYzItMDIxOWI0OTFjZGRhN2VlLTRjNjU3YjU4LTEzMjcxMDQtMTkwMjRjMTdjMDM4YzEifQ%3D%3D%22%2C%22history_login_id%22%3A%7B%22name%22%3A%22%22%2C%22value%22%3A%22%22%7D%2C%22%24device_id%22%3A%2219024c17c022c2-0219b491cdda7ee-4c657b58-1327104-19024c17c038c1%22%7D',
}

headers = {
    'Accept': 'application/json, text/plain, */*',
    'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive',
    'DNT': '1',
    'Pragma': 'no-cache',
    'Referer': 'https://www.swhysc.com/swhysc/financial/marginTradingList?channel=00010017000300020001&listId=2',
    'Sec-Fetch-Dest': 'empty',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Site': 'same-origin',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0',
    'sec-ch-ua': '"Not/A)Brand";v="8", "Chromium";v="126", "Microsoft Edge";v="126"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
}

params = {
    'secuCode': '',
    'market': '',
    'orderFlag': '',
    'pageNum': '1',
    'pageSize': '10',
}

response = requests.get(
    'https://www.swhysc.com/swhysc/interface/dsinfo/v1/margin/deposit/ratio',
    params=params,
    cookies=cookies,
    headers=headers,

)

# 检查响应状态码
if response.status_code == 200:
    try:
        # 获取响应内容的UTF-8解码字符串
        response_text = str(response.content.decode('utf-8'))
        print(type(response_text))
        decrypted_text = execjs.compile(open('./decrypt.js', 'r', encoding='utf-8').read()).call('decrypt',
                                                                                                 response_text)
        # 打印解密后的文本
        print("Decrypted response:", decrypted_text)

    except execjs.ProgramError as e:
        print(f"JavaScript error: {e}")
    except FileNotFoundError:
        print("JavaScript file 'decrypt.js' not found.")
    except UnicodeDecodeError as e:
        print(f"Encoding error: {e}")
    except ValueError as e:
        print(f"Value error: {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
else:
    print(f"Failed to fetch data: {response.status_code}")
// @charset "UTF-8";

const CryptoJs = require('crypto-js');

function decrypt(t) {
    // return typeof t.replace(/\s+/g, '')
    // t = t.replace(/\s+/g, '')
    // 判断t是否为空
    // if (t === '' || t === null || t === undefined) {
    //     return 't为空'
    // }
    var n = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : ""
        , r = 'rewin-swhysc1234'
        , i = CryptoJs.enc.Utf8.parse(r)
        , o = CryptoJs.AES.decrypt(t, i, {
        mode: CryptoJs.mode.ECB,
        padding: CryptoJs.pad.Pkcs7
    });
    return CryptoJs.enc.Utf8.stringify(o).toString()
}

// // var ans = decrypt('I9Z12I0KnbyLBPtcgpYe7w48OHv1UCCmgTdiBdxFCN/2 YdTCn2m2UO3L20J8MUhRWkTnWM2t3JYft4y8sbT2uFfJGT/qAw3ufFlagtl3WrksWKyIr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ILrmcuAf3SQ3Lzi0uFvaiisl4s8hH+GyGCcdsZ2w3Dwe2yFh6o1wHF15joLeqxGAh5EenqHpBgLjqRvnivK/lqgBIuNtJxlAY8Ec0h5nkp3DOPTSe5JO8QOPa0CDPzY/KYRVwptDi/CNU8prx0PmycbtW+LH6dU5vkOvofzkF23dfk82zbzHnLdPItGdsNw8HtshYeqNcBxdeY6C3qsRgIeRHp6h6QYC46kb54ryv5aoASLjbScZQGPBHNIeZ5Kdwzj00nuSTvEDj2tAgz82PymEVcKbQ4vwjVPKYcQuyFY8G7wTZxum9a2V1S8xxN7ueChtOgQTljc5MO3YfCmazrOsosvym7EEKyhm21LeSqEmvORLQhOA8UkJBQk3KCHdli/IrNTryK2S+gkLfjNJ18iIz/6 J7Ey/rjNOq2bwJ6/rhcT0Mi8B00PwT39ezVkikOyo9oNJ2D6rACsAeND2PPeK8B2oWjquKYLqpWh62/Vv+sunWhY9ufBzVSoYtnsxTK3xPuVtozXjSdncTOjc2anlMGX6chWnYmKfG8f3EphHBP2wk1Q/5 VonCD2Xmkd1xQpqYfh+P6lXeG9a1zvmKPXa5aSB //eVlLdtwQuiva3JxUfgjZg3OU9r4ddfWzJCC6ISelC8tVGz3cO28z8QMxCLnRh8k1GHEkv6MH0HdTpni3QaeEFuFfBaUUZ3Ay73q6jDolMiufrP7V/NGQtrR8+G0lge3XTyDhoXY='
// data = data.replace(/\s+/g, '')
// ans = decrypt(data)
// console.log(ans)

我首先对参数进行了确认,确认参数为正确格式,且值为正常的。

    // return typeof t.replace(/\s+/g, '')
    // t = t.replace(/\s+/g, '')
    // 判断t是否为空
    // if (t === '' || t === null || t === undefined) {
    //     return 't为空'
    // }

其次关于编码问题
我在js顶端加了
// @charset "UTF-8";
在Python中用的



# 设置默认编码为utf-8
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

# 检查响应状态码
if response.status_code == 200:
    try:
        # 获取响应内容的UTF-8解码字符串
        response_text = str(response.content.decode('utf-8'))
        print(type(response_text))
        decrypted_text = execjs.compile(open('./decrypt.js', 'r', encoding='utf-8').read()).call('decrypt',
                                                                                                response_text)
     
阅读 922
avatarAI BotBETA

Python中运行JavaScript代码通常是通过使用第三方库,如execjs,该库可以允许你编译和运行JavaScript代码。当在Python中运行JavaScript代码时遇到错误,可能有多种原因。

根据你提供的代码和错误截图,有几个潜在的问题点可以检查:

  1. JavaScript环境依赖execjs在背后使用了一个JavaScript运行环境(例如Node.js或V8),确保你的系统中已经安装了相应的运行环境,并且execjs能够找到它。
  2. JavaScript代码错误:尽管你尝试通过打印和检查参数t的类型来排除错误,但可能还有其他的JavaScript代码问题。例如,在解密函数中,如果输入的t不是有效的AES加密字符串,或者密钥r不正确,或者加密参数(如模式或填充)不匹配,解密过程可能会失败。
  3. Python与JavaScript交互问题:当你从Python传递字符串到JavaScript时,需要确保字符串的编码和格式是JavaScript函数所期望的。在你的Python代码中,你已经尝试使用UTF-8编码来解码响应内容,这是正确的做法。
  4. 异常处理:虽然你已经有一些异常处理,但可能还有其他未捕获的异常或错误。例如,如果execjs在尝试编译或运行JavaScript代码时遇到问题,可能会抛出其他类型的异常。
  5. execjs.ProgramError:这个异常通常表明JavaScript代码在执行时遇到了错误。错误信息应该包含在异常对象中,但截图没有显示完整的错误信息。你需要查看完整的错误消息来确定JavaScript代码中具体哪个部分出错了。

为了解决这个问题,你可以尝试以下步骤:

  • 检查完整的错误消息:在except execjs.ProgramError as e块中,打印出完整的错误消息e,这将提供有关JavaScript中发生错误的更多详细信息。
  • 验证JavaScript代码:单独运行JavaScript代码(例如,在Node.js环境中),并确保它可以成功解密你提供的输入。
  • 检查环境配置:确保你的Python环境配置正确,并且execjs能够找到并正确使用JavaScript运行时。
  • 审查加密/解密过程:确保加密和解密使用的密钥、模式和填充方式都是匹配的。

最后,由于你提供的信息有限,特别是错误截图没有显示完整的错误消息,所以这些只是一些可能的解决步骤。解决这个问题的关键在于查看完整的错误消息,并根据错误消息中的具体信息来确定问题的根源。

1 个回答

对应的Python代码

from Crypto.Cipher import AES
import base64

def decrypt(ciphertext):
    key = b'rewin-swhysc1234'
    cipher = AES.new(key, AES.MODE_ECB)
    plaintext = cipher.decrypt(base64.b64decode(ciphertext))
    return plaintext.decode('utf-8')

另外,一个小小的建议
image.png
image.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏