When parsing XML files using Python, parsing is ok if the header file of the XML file is encoded in the UTF-8 format, but if it is the other format, the following exception will appear:
Xml.parsers.expat.ExpatError:unknown encoding
Therefore, in order to ensure the normal operation of the program, we need to encode the read file.
1, first will read the characters from the original encoding parsing, and encoded into utf-8;
2, modify the XML encoding;
The code is as follows:
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:# encode string encoding _str = unquote (_str) _str = _ Str.decode (' GBK '). Encode (' Utf-8 ') print _str[0:100]except exception,ex:print ' ERROR ' # Modify the encoding of the XML file _STR = re.sub (' GBK ' , ' Utf-8 ', _str) xmldoc = etree.fromstring (_str) childlist = Xmldoc.getchildren () for node in childlist:str_value = Node.fin D ("Display/url"). Textif str_value.find (' CDATA ')! = -1:print ' haha '
The output results are as follows:
<?xml version= "1.0" encoding= "GBK"?><document><item><key> pertussis </key><display> <title><?xml version= "1.0" encoding= "Utf-8"?><document><item><key> pertussis </key> <display>
Python parsing XML file encountered encoding parsing problem