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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM