程序员

Python 爬虫 & requests & b

2018-05-17  本文已影响157人  CoderHG

一段简单,却被坑过得代码:

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转 bytes  的方式
    htmlBytes = bytes(bytearray(htmlText, encoding='utf-8'))
    print(htmlBytes)

    # bytes 转 str  的方式
    htmlStr = str(htmlBytes, encoding='utf-8')
    print(htmlStr)

    print('函数结束')


# 程序入口
if __name__ == '__main__':
    htmlRequest()

image.png

要注意类型,其实 Python 也与 OC 一样,如果把 bytes 当做 str 使用的话会抛出异常。

上一篇 下一篇

猜你喜欢

热点阅读