compare response.text and string failed in python

Question:

I have a mission to filter response whether it’s a normal response or not.

I should log the response if response.text is not'<Br>No match<br>OK!!'.

if not response.text == '<Br>No match<br>OK!!':
    logger.info('ERROR!!')

But I still can check the error message in log file which is '<Br>No match<br>OK!!'

I fixed my code as bellow but It doesn’t work.

if not str(response.text) == '<Br>No match<br>OK!!':
    logger.info('ERROR!!')

There was the other message in response.text that encoded with ISO-8859-1. Centain text in the log was broken so I could get the right text like normalize('NFC', msg).encode('ISO-8859-1').decode('cp949').

u'hello' == 'hello'.encode('ISO-8859-1').decode('cp949')  # True

Is there any problem with my code? Or what should I check more? please help me.

Asked By: Lazyer

||

Answers:

The problem with your code is that the response.text string is not in the same encoding format as the string you’re comparing it to.

The first thing to check is the encoding of the response.text and the string that you’re comparing it to. It seems that the response.text is in ISO-8859-1 encoding, while the string you’re comparing it to is in a different encoding format.

You can use the .encode(‘ISO-8859-1’) method on the string you’re comparing it to and the .decode(‘cp949’) method on the response.text variable to ensure that both strings are in the same encoding format.

if not response.text.decode('cp949') == '<Br>No match<br>OK!!'.encode('ISO-8859-1'):
    logger.info('ERROR!!')

Another thing to check is the actual response message. It may contain additional characters or spaces that make the comparison fail. You can check the message using the print function or check the response.content property, which returns the content of the response in bytes format.

print(response.text)

Additionally, you could use a regular expression to match the desired string and ignore any additional characters, spaces or line breaks.

import re

if not re.search(r'<Br>No match<br>OK!!', response.text):
    logger.info('ERROR!!')

In summary, the problem with your code is that the response.text is in a different encoding format, so you need to make sure that both strings are in the same format before comparing them, or use a regular expression to match the desired string.

Answered By: planet260
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.