一段簡單,卻被坑過得代碼:
import requests
def htmlRequest():
html = requests.get('http://baidu.com')
print(html)
# 這是一個文本 str
htmlText = html.text
print(htmlText)
# 這是一個 bytes
htmlContent = html.content
print(htmlContent)
# str轉(zhuǎn) bytes 的方式
htmlBytes = bytes(bytearray(htmlText, encoding='utf-8'))
print(htmlBytes)
# bytes 轉(zhuǎn) str 的方式
htmlStr = str(htmlBytes, encoding='utf-8')
print(htmlStr)
print('函數(shù)結(jié)束')
# 程序入口
if __name__ == '__main__':
htmlRequest()

image.png
要注意類型,其實 Python 也與 OC 一樣,如果把 bytes 當做 str 使用的話會拋出異常。