標籤:
使用python對xml檔案進行解析的時候,如果xml檔案的標頭檔是utf-8格式的編碼,那麼解析是ok的,但如果是其他格式將會出現如下異常:
xml.parsers.expat.ExpatError: unknown encoding
因此,為了保證程式的正常運行,我們需要對讀取的檔案進行編碼處理。
1、首先將讀取的字元從原來的編碼解析,並編碼成utf-8;
2、修改xml的encoding;
代碼如下:
import sysimport osimport datetimeimport timeimport stringfrom urllib import unquoteimport MySQLdbimport xml.parsers.expatimport xml.etree.ElementTree as Etreeimport typesimport httplibimport urllib2import urllibimport jsonimport redef readDataFromNetwork(url):req = urllib2.Request(url)rd = urllib2.urlopen(req)readData = rd.read()return readData# <![CDATA[ http://j.xywy.com/il_sii_27.htm ]]>def parseXmlStr(_str):try:# 將字串進行解碼編碼_str = unquote(_str)_str = _str.decode('gbk').encode('utf-8')print _str[0:100]except Exception,ex:print 'error'# 修改xml檔案的編碼方式_str = re.sub('gbk', 'utf-8', _str)xmlDoc = Etree.fromstring(_str)childList = xmlDoc.getchildren()for node in childList:str_value = node.find("display/url").textif str_value.find('CDATA') != -1:print 'haha'
輸出結果如下:
<?xml version="1.0" encoding="gbk" ?><DOCUMENT><item><key>百日咳</key><display><title><?xml version="1.0" encoding="utf-8" ?><DOCUMENT><item><key>百日咳</key><display>
Python解析xml檔案遇到的編碼解析的問題