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 = 'https://ifanyi.iciba.com/index.php?c=trans&m=fy&client=6&auth_user=key_ciba&sign=37218aa29f55fdcc'        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 '        }        self.data = {            'from': 'zh',            'to': 'en',            'q': word        }    def get_data(self):        #  Use post Method to send a post request ,data Dictionary for request body         response = requests.post(self.url, data=self.data, 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 ')    # king.run()    word = input(' Please enter the word or sentence to be translated :')    king = King(word)    king.run(

Operation results and error reporting contents
print(dict_data['content']['out'])
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.
https://en.primo.wiki/2022/02/202202021314581766.html

Random recommended