current position:Home>Run result and error content Print (dict_data ['content '] ['out']) keyerror: 'content, how to solve it?

Run result and error content Print (dict_data ['content '] ['out']) keyerror: 'content, how to solve it?

2022-02-02 13:15:00 CSDN Q & A

This is the code I wrote

import requestsimport jsonclass King(object):    def __init__(self, word):        self.url = ''        self.headers = {            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '                          'Chrome/96.0.4664.45 Safari/537.36 '        } = {            'from': 'zh',            'to': 'en',            'q': word        }    def get_data(self):        #  Use post Method to send a post request ,data Dictionary for request body         response =,, headers=self.headers)        return response.content    def parse_data(self, data):        # loads Methods will json The string is converted to pyton Dictionaries         dict_data = json.loads(data)        print(dict_data['content']['out'])    def run(self):        #  Writing crawler logic         # url        # headers        # data Dictionaries         #  Send request to get response         response = self.get_data()        # print(response)        #  Data analysis         self.parse_data(response)if __name__ == '__main__':    # king = King(' Dictionaries ')    #    word = input(' Please enter the word or sentence to be translated :')    king = King(word)

Operation results and error reporting contents
KeyError: 'content'

Refer to the answer 1:

have a look dict_data Is it right? None 了 , print Come out and see if there's any content This key

Refer to the answer 2:

copyright notice
author[CSDN Q & A],Please bring the original link to reprint, thank you.

Random recommended