一段簡(jiǎn)單焰情,卻被坑過(guò)得代碼:
import requests
def htmlRequest():
html = requests.get('http://baidu.com')
print(html)
# 這是一個(gè)文本 str
htmlText = html.text
print(htmlText)
# 這是一個(gè) 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
要注意類型陌凳,其實(shí) Python 也與 OC 一樣,如果把 bytes 當(dāng)做 str 使用的話會(huì)拋出異常烙样。