playwright+AI大模型分析接口返回内容是否包含敏感信息

写这个主要是为了用户安全,怕有一些接口返回了用户的个人信息等,被别人爬虫或者什么手段利用了,当然你也可以测试一些别的你想找的接口返回内容

先附上结果内容展示playwright+AI大模型分析接口返回内容是否包含敏感信息_第1张图片

生成txt文件,展示接口地址、返回内容、以及是否包含敏感内容(当然这里判断是否为敏感内容是自己定义的prompt,我这里就写了姓名并不是敏感信息,你也可以自己进行编辑,什么内容是你需要找到敏感信息)

附脚本代码

import datetime
import re

from playwright.sync_api import Playwright, sync_playwright
from langchain_openai import ChatOpenAI
import nest_asyncio
nest_asyncio.apply()

prompt='''
    接口分析机器人,根据接口的返回内容,分析接口返回内容是否合理,接口返回内容无异常仅返回接口正常,
    如果返回内容包含个人信息等敏感字段则返回异常内容
    注:姓名不属于敏感信息
'''

def get_response(test):
    llm = ChatOpenAI(
        api_key="xxxxxxxxxxxxxxxxxxx",  # 如果您没有配置环境变量,请用百炼API Key将本行替换为:api_key="sk-xxx"
        base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",  # 填写DashScope base_url
        model="qwen-max-latest"
        )
    messages = [
        {"role": "system", "content": prompt},
        {"role": "user", "content": test},
    ]
    response = llm.invoke(messages)
    return response.content


def run(playwright: Playwright) -> None:
    filename = "output" + str(int(datetime.datetime.now().timestamp())) + ".txt"
    file = open(filename, 'w',encoding="utf-8")
    # 启动浏览器
    browser = playwright.chromium.launch(headless=False)
    context = browser.new_context()
    context.set_default_timeout(60000)  # 全局默认超时 60 秒
    # 创建一个新的页面
    page = context.new_page()

    # 监听所有的网络响应
    def handle_response(response):
        # 响应以api开头的接口
        if response.url.startswith('https://www.baidu.com/api'):
            try:
                # 尝试解析JSON响应体
                json_body = response.json()
                # 在这里处理解析后的JSON数据,例如打印、保存或进一步分析
                # print(f"Response Body (JSON): {json_body}")
                api_content = f"接口为{response.url}接口返回内容为{json_body}"
                # 调用大模型判断接口返回内容是否合理
                res = get_response(api_content)
                file.write(f"Response URL: {response.url}, Status Code: {response.status}" + "\n")
                file.write(f"Response Body: {json_body}" + "\n")
                file.write("大模型判断内容:" + res + "\n")
                file.write("========================================================================"
                           "==================================================================\n")
            except Exception as e:
                # 如果不是JSON格式,则打印错误信息和原始文本响应体
                print(f"Error parsing JSON: {e}")
                print(f"Response Body (not JSON): {response.text()}")

    page.on("response", handle_response)
#以下为欲运行的自动化脚本内容
    page.goto("https://www.baidu.com/")

with sync_playwright() as playwright:
    run(playwright)

使用自己的大模型key与大模型地址

最下边注释部分用来大家自己录制脚本并把自己的自动化脚本内容粘贴上去(录制命令:playwright codegen https://www.baidu.com/  ,其他内容详见playwright官方功能),playwright自动执行脚本的同时会获取所有以api开头的接口(这里可以根据自己的项目自己定义,我们项目中后端的接口都是以api开头的)

也可以把这个脚本写成方法,放入自己的playwright自动化脚本项目中,在跑自动化脚本内容的同时可以获取接口的返回内容,并对返回内容进行你自定义的检索、校验

(ps:菜鸡随便记录一下)

你可能感兴趣的:(自动化,python)