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"))

 

posted @ 2018-10-05 21:28  Ryan_zheng  阅读(2897)  评论(0编辑  收藏  举报