Python 字节与字符串的转换

html = urlopen("http://www.cnblogs.com/ryanzheng/p/9665224.html")
bsObj = BeautifulSoup(html, features="lxml")
with open('cnblog.html', 'wt') as fout:
    fout.write(bsObj)

由于 BeautifulSoup 返回的字符是以字节的形式,所以无法直接写入文件,

若直接将 bsObj 写入文件,会出现如下错误:

提示 write() 只能接受 str 字符串类型的参数,而不是 BeautifulSoup 类型

所以需要将 BeautifulSoup 转换为 str

html = urlopen("http://www.cnblogs.com/ryanzheng/p/9665224.html")
bsObj = BeautifulSoup(html, features="lxml")
with open('cnblog.html', 'wt') as fout:
    fout.write(bsObj.decode("utf-8"))
原文地址:https://www.cnblogs.com/ryanzheng/p/9745955.html