美文网首页程序员
Python 爬虫 & requests & b

Python 爬虫 & requests & b

作者: CoderHG | 来源:发表于2018-05-17 22:04 被阅读157次

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

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 使用的话会抛出异常。

相关文章

网友评论

    本文标题:Python 爬虫 & requests & b

    本文链接:https://www.haomeiwen.com/subject/ornidftx.html