百度文心一言测试版接口分析

# !/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
@author  : [email protected]
@des     :

"""
import requests
import json
import re


class BDWX():
    """
    文心一言接口解析
    """
    def __init__(self):
        self.headers = {
            "Content-Type": "application/json",
            "Referer": "https://yiyan.baidu.com/",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36",
        }
        # 换成自己的 BDUSS
        self.cookies = {
            "BDUSS": "I3TTZCM3gxLTVzZm44dmlnLWN-Q2ZQNmRScm5MR3REcENERVFrZEc0Wmlwd3RsRVFBQUFBJCQAAAAAAAAAAAEAAAAQdrtY0fS54rXE37nfud-537kAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGIa5GRiGuRkZk"
        }

        self.base_url = "https://yiyan.baidu.com/eb/chat/conversation/v2"

    def get_data(self, query):
        """
        请求数据
        :param query:
        :return:
        """
        data = {
            "text": "{}".format(query),
            "timestamp": 1692670879294,
        }
        data = json.dumps(data, separators=(',', ':'))
        response = requests.post(
            self.base_url,
            headers=self.headers,
            cookies=self.cookies,
            data=data)
        return response.text

    def anlise_data(self, data,query):
        """
        解析数据
        :param data:
        :return:
        """
        res = re.findall("event:message\ndata:(.*)", data)
        for i in res:
            content = json.loads(i)["data"]["content"]
            if query.startswith("画"):
                img_url = re.findall('
'
, content)[0] yield img_url else: yield content def process(self,query): """ 处理逻辑 没加异常捕获(正常情况基本不会有异常) :param query: :return: """ data = self.get_data(query) for content in self.anlise_data(data,query): print(content,end="") if __name__ == '__main__': bdwx = BDWX() while True: bdwx.process("你能做什么") print()

你可能感兴趣的:(python)