[lxml] 換成 python3 之後的 tostring 問題

  • 3924
  • 0

原本在 python2 的時候,lxml 要序列化,只要呼叫 tostring,但到 python 3 就會出問題

原本在 python2 的時候,lxml 要序列化,只要呼叫 tostring,就可以交給檔案物件寫進檔案,像是這樣:

f = open('test.xml', 'w')
f.write(etree.tostring(root))

換到在 python3 的時候,就會發生:

f.write(etree.tostring(root))
TypeError: write() argument must be str, not bytes

原因是 lxml 回傳的是 python3 的新型態 bytes,其實就是以前的 str 型態。
要解決有兩個方法。
一個是 tostring 成 unicode,像這樣

f = open('test.xml', 'w')
f.write(etree.tostring(root))

另一個方法是

f = open('test.xml', 'wb')
f.write(etree.tostring(root))

以我們有中文需求的話,我比較喜歡第一種。

 

 

 

分享