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