【POST请求-腾讯翻译君-爬虫案例】

原因:尝试多个在线翻译平台,由于返回数据存在加密原因(暂时不会解密),最总找到 ”腾讯翻译君“ 完成爬虫案例POST请求测试

案例测试网址

  • 腾讯翻译 :https://fanyi.qq.com/
import requests
import json


class Search():

    def __init__(self,  word) -> None:

        self.url = "https://fanyi.qq.com/api/translate"

        self.headers = {
            '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'
        }

        self.data = {
            'source': 'auto',
            'target': 'en',
            'sourceText': word,
            'qtv': 'd6b80aee23530d6d',
            'qtk': 'YEYhu1zSCa2JbdJ16xeGfH12oAHABTokH8NMzPVriyAqD0nbaHOA7BEF3naAeSImmaRMOdAmb2xaToIjtFfitIPLNg3UIbmQLhgXKfnM46FG0s5bngRWAE6tzq6k0g/2XMIGR/JPbIzGelVDqqaZuw==',
            'sessionUuid': 'translate_uuid1696487685473'
        }

    def post_data(self):
        response = requests.post(
            self.url, headers=self.headers, data=self.data)

        # print(response)  打印

        return response.content

    def parse_data(self, data):

        # loads方法将json字符串转换成python字典

        dict_data = json.loads(data)

        print(dict_data['translate']['records'][0]['targetText'])

        # records使用列表格式获取

    def run(self):

        # 编辑爬虫逻辑

        # url

        # headers

        # data 字典

        # 发送请求响应
        response = self.post_data()

        print(response)  # 打印返回结果字符串
        print("*" * 50)

        # 数据解析
        self.parse_data(response)


if __name__ == '__main__':

    word = input("请输入要翻译的单词或句子:")

    search = Search(word)

    search.run()



"""
    "translate": {
        "errCode": 0,
        "errMsg": "",
        "sessionUuid": "translate_uuid1696487685473",
        "source": "zh",
        "target": "en",
        "records": [
            {
                "sourceText": "时间",
                "targetText": "time",
                "traceId": "1e15f8dc9fcd49b795128356b853db58"
            }
        ],
        "full": true,
        "options": {}
    }
"""

你可能感兴趣的:(爬虫)