The solution to garbled characters using the requests module in python

One: why there are garbled characters

In the learning of python, we often encounter garbled characters. The reason for the garbled characters is that Python is inreadThe default decoding method is to use the operating system encoding, if andThe encoding method is different when saving,Right nowIncompatible character encoding formats, garbled characters will appear.

Two: Three ways to solve the problem

method one


import requests
url='https://www.baidu.com/'
response = requests.get(url)
response.encoding='utf8'   #第一种方法,指定编码为utf-8
print(response)   # 打印状态码
print(response.text)

Method Two


import requests
url='https://www.baidu.com/'
response = requests.get(url)
response.encoding=response.apparent_encoding    # 第二种方法,自动识别文本编码
print(response)   # 打印状态码
print(response.text)

method three


import requests
url='https://www.baidu.com/'
response = requests.get(url)
print(response)   # 打印状态码
print(response.content.decode())  # 第三种方法

Guess you like

Origin blog.csdn.net/m0_74459049/article/details/130538823