예제 #1
0
    def photo_query(self, query):
        data = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><RetrieveImages xmlns="NWMLS:EverNet"><query>{0}</query></RetrieveImages></soap:Body></soap:Envelope>'.format(escape(query))
        response = session.post('http://images.idx.nwmls.com/imageservice/imagequery.asmx', headers = {
          'Content-Type': 'text/xml; charset=utf-8',
          'Soapaction':'NWMLS:EverNet/RetrieveImages',
        }, data=data, timeout=30, stream=True)
        logger.debug('>>> %s' % data)

        with tempfile.TemporaryFile() as response_file:
            tmp = response.raw.read(1000)
            while tmp:
                response_file.write(tmp)
                tmp = response.raw.read(1000)
                logger.debug('<<< %s' % tmp)
            response_file.seek(0)

            self.data = tempfile.TemporaryFile()
            self.in_envelope = False
            p = ParserCreate()
            p.StartElementHandler = self._start_element_get_envelope
            p.EndElementHandler = self._end_element_get_envelope
            p.CharacterDataHandler = self._char_data_get_envelope
            p.ParseFile(response_file)
        self.data.seek(0)
        return self.data
예제 #2
0
    def __init__(self):
        self.recent_files = []
        self.tlist = []
        self.item = None

        fname = os.path.expanduser(GRAMPS_FILENAME)
        if not os.path.exists(fname):
            return # it's the first time gramps has ever been run

        try:
            with open(fname, "rb") as xml_file:
                if USE_LOCK:
                    fcntl.lockf(xml_file, fcntl.LOCK_SH)

                parser = ParserCreate()
                parser.StartElementHandler = self.start_element
                parser.EndElementHandler = self.end_element
                parser.CharacterDataHandler = self.characters
                parser.ParseFile(xml_file)
            # all advisory locks on a file are released on close
        except IOError as err:
            logging.warning(
                _("Unable to open list of recent DBs file {fname}: {error}"
                 ).format(fname=fname, error=err))
        except ExpatError as err:
            logging.error(
                _("Error parsing list of recent DBs from file {fname}: "
                  "{error}.\nThis might indicate a damage to your files.\n"
                  "If you're sure there is no problem with other files, "
                  "delete it, and restart Gramps."
                 ).format(fname=fname, error=err))
예제 #3
0
    def photo_query(self, query):
        data = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><RetrieveImages xmlns="NWMLS:EverNet"><query>{0}</query></RetrieveImages></soap:Body></soap:Envelope>'.format(
            escape(query)
        )
        import socket

        socket.setdefaulttimeout(30)
        conn = httplib.HTTPConnection("images.idx.nwmls.com", timeout=30)
        conn.putrequest("POST", "/imageservice/imagequery.asmx")
        conn.putheader("Content-Type", "text/xml; charset=utf-8")
        conn.putheader("Soapaction", "NWMLS:EverNet/RetrieveImages")
        conn.putheader("Content-Length", "%d" % len(data))
        conn.endheaders()
        conn.send(data)
        logger.debug(">>> %s" % data)

        with tempfile.TemporaryFile() as response_file:
            response = conn.getresponse()
            tmp = response.read(1000)
            while tmp:
                response_file.write(tmp)
                tmp = response.read(1000)
                logger.debug("<<< %s" % tmp)
            response_file.seek(0)

            self.data = tempfile.TemporaryFile()
            self.in_envelope = False
            p = ParserCreate()
            p.StartElementHandler = self._start_element_get_envelope
            p.EndElementHandler = self._end_element_get_envelope
            p.CharacterDataHandler = self._char_data_get_envelope
            p.ParseFile(response_file)
        self.data.seek(0)
        return self.data
예제 #4
0
파일: dae.py 프로젝트: daid/Cura2
    def __init__(self, filename):
        self.mesh = Mesh()
        self.mesh.metaData['filename'] = filename
        self.volume = self.mesh.newVolume()

        r = ParserCreate()
        r.StartElementHandler = self._StartElementHandler
        r.EndElementHandler = self._EndElementHandler
        r.CharacterDataHandler = self._CharacterDataHandler

        self._base = {}
        self._cur = self._base
        self._idMap = {}
        self._geometryList = []
        self._faceCount = 0
        r.ParseFile(open(filename, "r"))
        
        self.vertexCount = 0
        for instance_visual_scene in self._base['collada'][0]['scene'][0]['instance_visual_scene']:
            for node in self._idMap[instance_visual_scene['_url']]['node']:
                self._ProcessNode1(node)
        self.volume._prepareFaceCount(self._faceCount)
        for instance_visual_scene in self._base['collada'][0]['scene'][0]['instance_visual_scene']:
            for node in self._idMap[instance_visual_scene['_url']]['node']:
                self._ProcessNode2(node)

        scale = float(self._base['collada'][0]['asset'][0]['unit'][0]['_meter']) * 1000
        self.volume.vertexData *= scale
        
        self._base = None
        self._cur = None
        self._idMap = None
        
        self.volume.calculateNormals()
예제 #5
0
파일: dae.py 프로젝트: EFinley/Cura
	def load(self, filename):
		r = ParserCreate()
		r.StartElementHandler = self._StartElementHandler
		r.EndElementHandler = self._EndElementHandler
		r.CharacterDataHandler = self._CharacterDataHandler

		self._base = {}
		self._cur = self._base
		self._idMap = {}
		self._geometryList = []
		r.ParseFile(open(filename, "r"))
		
		self.vertexCount = 0
		for instance_visual_scene in self._base['collada'][0]['scene'][0]['instance_visual_scene']:
			for node in self._idMap[instance_visual_scene['_url']]['node']:
				self._ProcessNode1(node)
		self._prepareVertexCount(self.vertexCount)
		for instance_visual_scene in self._base['collada'][0]['scene'][0]['instance_visual_scene']:
			for node in self._idMap[instance_visual_scene['_url']]['node']:
				self._ProcessNode2(node)

		scale = float(self._base['collada'][0]['asset'][0]['unit'][0]['_meter']) * 1000
		self.origonalVertexes *= scale
		
		self._base = None
		self._cur = None
		self._idMap = None
		
		self._postProcessAfterLoad()
		return self
예제 #6
0
 def get_parser(self):
     p = ParserCreate()
     p.buffer_text = True
     p.StartElementHandler = self.start_element
     p.EndElementHandler = self.end_element
     p.CharacterDataHandler = self.char_data
     return p
예제 #7
0
    def listing_query(self, query):
        data = '<?xml version="1.0" encoding="UTF-8"?><SOAP-ENV:Envelope xmlns:ns0="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://www.nwmls.com/EverNetServices" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Header/><ns0:Body><ns1:{0}><ns1:v_strXmlQuery>{1}</ns1:v_strXmlQuery></ns1:{0}></ns0:Body></SOAP-ENV:Envelope>'.format(self.endpoint, escape(str(query)))

        response = session.post('http://evernet.nwmls.com/evernetqueryservice/evernetquery.asmx', headers = {
            'Soapaction': "http://www.nwmls.com/EverNetServices/{0}".format(self.endpoint),
            'Content-Type': 'text/xml; charset=utf-8',
        }, timeout=60*5, data=data, stream=True)

        logger.info('Sent request...')
        logger.debug('>>> %s' % data)

        with tempfile.TemporaryFile() as response_file:
            tmp = response.raw.read(1000)
            logger.info('Receiving data...')
            while tmp:
                response_file.write(tmp)
                tmp = response.raw.read(1000)
                logger.debug('<<< %s' % tmp)
            response_file.seek(0)

            self.data = tempfile.TemporaryFile()
            self.in_envelope = False
            p = ParserCreate()
            p.StartElementHandler = self._start_element_get_envelope
            p.EndElementHandler = self._end_element_get_envelope
            p.CharacterDataHandler = self._char_data_get_envelope
            response_file.seek(0)
            try:
                p.ParseFile(response_file)
            except ExpatError:
                logging.error("Error parsing XML response from Evernet.  This usually happens when the server returns an error message.  You can see the full response if you set the logging to DEBUG level")
                raise
        logger.info('All data received, starting parsing')
        self.data.seek(0)
        return self.data
예제 #8
0
def processReport(xmlFile):
  global reportData, tagStack

  guid = os.path.splitext(os.path.basename(xmlFile))[0]

  cursor = get_db().cursor()
  executeQuery(cursor,
              '''SELECT guid FROM #PFX#reports WHERE guid = %s''',
              (guid))
  report = cursor.fetchone()

  if report != None:
    os.remove(xmlFile)
    return

  source = open(xmlFile, 'rb')
  reportData = {'status': '', 'usefulness': 0, 'warnings': {}, 'requests': [], 'filters': [], 'subscriptions': [], 'extensions': [], 'errors': [], 'time': time()}
  tagStack = []

  parser = ParserCreate()
  parser.StartElementHandler = processElementStart
  parser.EndElementHandler = processElementEnd
  parser.CharacterDataHandler = processText
  try:
    parser.ParseFile(source)
  except ExpatError, error:
    reportData['warnings']['!parsing'] = 'Parsing error in the report: %s at line %i column %i' % (ErrorString(error.code), error.lineno, error.offset)
예제 #9
0
파일: dae.py 프로젝트: AJMartel/3DPrinter
	def __init__(self, filename):
		self.obj = mesh.printableObject(os.path.basename(filename))
		self.mesh = self.obj._addMesh()

		r = ParserCreate()
		r.StartElementHandler = self._StartElementHandler
		r.EndElementHandler = self._EndElementHandler
		r.CharacterDataHandler = self._CharacterDataHandler

		self._base = {}
		self._cur = self._base
		self._idMap = {}
		self._geometryList = []
		self._faceCount = 0
		r.ParseFile(open(filename, "r"))
		
		self.vertexCount = 0
		for instance_visual_scene in self._base['collada'][0]['scene'][0]['instance_visual_scene']:
			for node in self._idMap[instance_visual_scene['_url']]['node']:
				self._ProcessNode1(node)
		self.mesh._prepareFaceCount(self._faceCount)
		for instance_visual_scene in self._base['collada'][0]['scene'][0]['instance_visual_scene']:
			for node in self._idMap[instance_visual_scene['_url']]['node']:
				self._ProcessNode2(node)

		scale = float(self._base['collada'][0]['asset'][0]['unit'][0]['_meter']) * 1000
		self.mesh.vertexes *= scale
		
		self._base = None
		self._cur = None
		self._idMap = None
		
		self.obj._postProcessAfterLoad()
예제 #10
0
    def __init__(self):
        self.recent_files = []

        fname = os.path.expanduser(WEARNOW_FILENAME)
        if not os.path.exists(fname):
            return # it's the first time wearnow has ever been run

        try:
            with open(fname, "rb") as xml_file:
                if use_lock:
                    fcntl.lockf(xml_file,fcntl.LOCK_SH)

                p = ParserCreate()
                p.StartElementHandler = self.startElement
                p.EndElementHandler = self.endElement
                p.CharacterDataHandler = self.characters
                p.ParseFile(xml_file)
            # all advisory locks on a file are released on close
        except IOError as err:
            logging.warning(
                    _("Unable to open list of recent DBs file {fname}: {error}"
                        ).format(fname=fname, error=err))
        except Exception as err:
            logging.error(
                    _("Error parsing list of recent collections from file {fname}: {error}.\n"
                        "This might indicate a damage to your files.\n"
                        "If you're sure there is no problem with other files, "
                        "delete it, and restart ComfiSense."
                        ).format(fname=fname, error=err))
예제 #11
0
def parse_weather(xml):
    handler = WeatherSaxHandler()
    parser = ParserCreate()
    parser.StartElementHandler = handler.start_element
    parser.EndElementHandler = handler.end_element
    parser.CharacterDataHandler = handler.char_data
    parser.Parse(xml)
    return weather_dict
예제 #12
0
 def parse(self, fileobj):
     from xml.parsers.expat import ParserCreate
     parser = ParserCreate()
     parser.StartElementHandler = self.handleBeginElement
     parser.EndElementHandler = self.handleEndElement
     parser.CharacterDataHandler = self.handleData
     parser.ParseFile(fileobj)
     return self.root
예제 #13
0
def weather_parser(xml): 
    handler = WeatherSaxHandler()
    parser = ParserCreate()
    parser.StartElementHandler = handler.start_element
    parser.EndElementHandler = handler.end_element
    parser.CharacterDataHandler = handler.char_data
    parser.Parse(xml)
    print(handler.weather)
예제 #14
0
def parse_weather(data):
    parser = ParserCreate()
    handler = WeatherSaxHandler()
    parser.StartElementHandler = handler.start_e
    parser.EndElementHandler = handler.end_e
    parser.CharacterDataHandler = handler.c_data
    handler.init()
    parser.Parse(data)
    return handler.weather
예제 #15
0
파일: util.py 프로젝트: stuffonfire/breve
    def parse ( self, xmldata ):
        from xml.parsers.expat import ParserCreate

        p = ParserCreate ( 'utf-8' )
        p.StartElementHandler = self.start_element
        p.EndElementHandler = self.end_element
        p.CharacterDataHandler = self.char_data
        p.Parse ( xmldata )
        return '\n'.join ( self.output )
예제 #16
0
def xml_test():
    #操作XML有两种方法:DOM和SAX。
    #DOM会把整个XML读入内存,解析为树,因此占用内存大,解析慢,优点是可以任意遍历树的节点。
    #SAX是流模式,边读边解析,占用内存小,解析快,缺点是我们需要自己处理事件。
    
    #在Python中使用SAX解析XML非常简洁,通常我们关心的事件是start_element,end_element和char_data
    class DefaultSaxHandler(object):
        def __init__(self):
            self.weather = {}
            
        def start_element(self,name,attrs):
            if name=='yweather:location':
                self.weather['country'] = attrs['country']
                self.weather['city'] = attrs['city']
            if name=='yweather:astronomy':
                self.weather['sunrise'] = attrs['sunrise']
                self.weather['sunset'] = attrs['sunset']
                print(self.weather)
            #print('SAX: start_element:%s, attrs:%s' % (name,str(attrs)))
            
        def end_element(self,name):
            pass#print('SAX:end_element:%s' % name)
            
        def char_data(self,text):
            if not text:
                print('SAX:char_data:%s' % text)
            
    data = r'''<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
    <rss version="2.0" xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">
    <channel>
        <title>Yahoo! Weather - Beijing, CN</title>
        <lastBuildDate>Wed, 27 May 2015 11:00 am CST</lastBuildDate>
        <yweather:location city="Beijing" region="" country="China"/>
        <yweather:units temperature="C" distance="km" pressure="mb" speed="km/h"/>
        <yweather:wind chill="28" direction="180" speed="14.48" />
        <yweather:atmosphere humidity="53" visibility="2.61" pressure="1006.1" rising="0" />
        <yweather:astronomy sunrise="4:51 am" sunset="7:32 pm"/>
        <item>
            <geo:lat>39.91</geo:lat>
            <geo:long>116.39</geo:long>
            <pubDate>Wed, 27 May 2015 11:00 am CST</pubDate>
            <yweather:condition text="Haze" code="21" temp="28" date="Wed, 27 May 2015 11:00 am CST" />
            <yweather:forecast day="Wed" date="27 May 2015" low="20" high="33" text="Partly Cloudy" code="30" />
            <yweather:forecast day="Thu" date="28 May 2015" low="21" high="34" text="Sunny" code="32" />
            <yweather:forecast day="Fri" date="29 May 2015" low="18" high="25" text="AM Showers" code="39" />
            <yweather:forecast day="Sat" date="30 May 2015" low="18" high="32" text="Sunny" code="32" />
            <yweather:forecast day="Sun" date="31 May 2015" low="20" high="37" text="Sunny" code="32" />
        </item>
    </channel>
    </rss>
    '''
    handler = DefaultSaxHandler()
    parser = ParserCreate()
    parser.StartElementHandler = handler.start_element
    parser.EndElementHandler = handler.end_element
    parser.CharacterDataHandler = handler.char_data
    parser.Parse(data)
예제 #17
0
def process_one_file(filename):
    global my_article_terms
    print "Processing", filename
    p=ParserCreate()
    p.StartElementHandler=start_element
    p.EndElementHandler=end_element
    p.CharacterDataHandler=character_data
    my_article_terms={}
    p.ParseFile(gzip.GzipFile(filename))
    return my_article_terms
예제 #18
0
파일: test1.py 프로젝트: catleer/deeptest
def parseXml(xml_str):
    handler = DefaultSaxHandler()
    parser = ParserCreate()
    parser.StartElementHandler = handler.start_element
    parser.EndElementHandler = handler.end_element
    parser.CharacterDataHandler = handler.char_data
    parser.Parse(xml_str)
    return {
        'city': handler.location['city'],
        'forecast': handler.forecast
    }
예제 #19
0
    def init(cls):
        handler = DefaultSaxHandler()
        parser = ParserCreate()
        parser.StartElementHandler = handler.start_element
        parser.EndElementHandler = handler.end_element
        parser.CharacterDataHandler = handler.char_data

        with open(cls.config_file, 'r') as f:
            s = str(f.read())
            s = s.replace('\n', '')
            parser.Parse(s)
예제 #20
0
	def _expatParseFile(self, pathOrFile):
		parser = ParserCreate()
		parser.StartElementHandler = self.startElementHandler
		parser.EndElementHandler = self.endElementHandler
		parser.CharacterDataHandler = self.characterDataHandler
		if isinstance(pathOrFile, (bytes, basestring)):
			with open(pathOrFile) as f:
				parser.ParseFile(f)
		else:
			parser.ParseFile(pathOrFile)

		return self.getRoot()
예제 #21
0
    def __parse_xml(self):
        parser = ParserCreate()
        parser.returns_unicode = True
        parser.StartElementHandler = self.__start_element
        parser.EndElementHandler = self.__end_element
        parser.CharacterDataHandler = self.__char_data
        try:
            xml = urllib.urlopen(self.url).read()
        except:
            print 'new work unreadable'

        parser.Parse(xml)
예제 #22
0
파일: XML.py 프로젝트: zym1115718204/mygit
def read_xml():
    try:
        handler=DefaultSaxHandler()
        parser=ParserCreate()
        parser.returns_unicode = True
        parser.StartElementHandler = handler.start_element
        parser.EndElementHandler = handler.end_element
        parser.CharacterDataHandler = handler.char_data

        parser.Parse(xmldata)
    except:
        print 'read error!'
예제 #23
0
 def handle_namespaces(self, parser):
     """Do not check namespaces for grammars used by ns-specific tools."""
     if Language.get_language(self.file_name) in self.non_ns_types:
         xparser = ParserCreate()
         xparser.DefaultHandlerExpand = parser._default
         xparser.StartElementHandler = parser._start
         xparser.EndElementHandler = parser._end
         xparser.CharacterDataHandler = parser._data
         xparser.CommentHandler = parser._comment
         xparser.ProcessingInstructionHandler = parser._pi
         # Set the etree parser to use the expat non-ns parser.
         parser.parser = parser._parser = xparser
예제 #24
0
 def __call__(self):
     self.json, self.html = '',''
     parser = ParserCreate()
     parser.StartElementHandler = self.start_element
     parser.EndElementHandler = self.end_element
     parser.CharacterDataHandler = self.char_data
     try:
         data = self.datafunc()
         parser.Parse(data, 1)
     except:
         raise ParsingError
     return self.folder
 def parse(self, filename):
   """ Parse a file
   """
   # Initialise state
   self._stack = list()
   self._active = None
   # Allow custom state initialisation
   self.beginParse()
   # Create a parser and process the file
   parser = ParserCreate()
   parser.StartElementHandler = self._StartElementHandler
   parser.EndElementHandler = self._EndElementHandler
   parser.CharacterDataHandler = self._CharacterDataHandler
   parser.ParseFile(open(filename, "r"))
예제 #26
0
def my_test():
    xml = open('productrs.xml', 'r', encoding='utf-8')
    productrs = xml.read()
    handler = DefaultSAXHandler()
    # 创建解析器
    parser = ParserCreate()
    parser.StartElementHandler = handler.start_element
    parser.EndElementHandler = handler.end_element
    parser.CharacterDataHandler = handler.char_data
    productrsxml = parser.Parse(productrs)
    print(productrsxml)
    xml.close()
    print('========================')
    print(prdtrs)
예제 #27
0
def weixinpayactionDemo():
    nonce_str = weixinnonce_str()
    tradeno = weixintradeno()

    info = {"appid": APP_ID}
    info["mch_id"] = PARTNER_ID
    info["device_info"] = "ios"
    info["nonce_str"] = nonce_str
    info["body"] = "微微helloworld"
    info["detail"] = "gooddetail"
    info["out_trade_no"] = tradeno
    info["total_fee"] = "1"
    info["spbill_create_ip"] = "192.168.1.1"
    info["notify_url"] = notify_url
    info["trade_type"] = "APP"

    sign = weixinSign(info,PARTNER_KEY)
    info["sign"] = sign

    xml = transformToXML(info)
    request = weipayaction(xml)

    handler = DefaultSaxHandler()
    parser = ParserCreate()
    parser.StartElementHandler = handler.start_element
    parser.EndElementHandler = handler.end_element
    parser.CharacterDataHandler = handler.char_data
    parser.Parse(request)

    weixinresponse = handler.dict

    # if weixinresponse["return_code"] == "SUCCESS" and weixinresponse["return_msg"] == "SUCCESS":
    #     print("成功")
    # else:
    #     return json.dumps({"flag":"101","msg":weixinresponse["return_msg"]})

    print(weixinresponse)
    timestamp = "%d"%time.time()
    response = {"appid":weixinresponse["appid"],
                "partnerid":weixinresponse["mch_id"],
                "prepayid":weixinresponse["prepay_id"],
                "package":"Sign=WXPay",
                "noncestr":weixinresponse["nonce_str"],
                "timestamp":timestamp}
    responsesign = weixinSign(response,PARTNER_KEY)
    #传给客户端的sign 是现在这几个参数的签名,不是微信服务器返回的。
    response["sign"] = responsesign

    return json.dumps(response)
예제 #28
0
def parse(data):
    def start_el(name, attrs):
        ParsedXML['start'][name] = attrs

    def char_handler(data):
        patt = re.compile('\S+', re.UNICODE)
        if patt.search(data):
            ParsedXML['data'].append(data)

    ParsedXML = {'start': {}, 'end': [], 'data': []}
    parser = ParserCreate()
    parser.StartElementHandler = start_el
    parser.CharacterDataHandler = char_handler
    parser.Parse(data)
    return ParsedXML
예제 #29
0
	def _expatParseFile(self, pathOrFile):
		parser = ParserCreate()
		parser.returns_unicode = 0  # XXX, Don't remember why. It sucks, though.
		parser.StartElementHandler = self.startElementHandler
		parser.EndElementHandler = self.endElementHandler
		parser.CharacterDataHandler = self.characterDataHandler
		if isinstance(pathOrFile, (str, unicode)):
			f = open(pathOrFile)
			didOpen = 1
		else:
			didOpen = 0
			f = pathOrFile
		parser.ParseFile(f)
		if didOpen:
			f.close()
		return self.getRoot()
예제 #30
0
	def _parseFile(self, file):
		from xml.parsers.expat import ParserCreate
		parser = ParserCreate('utf-8')
		parser.StartElementHandler = self._startElementHandler
		parser.EndElementHandler = self._endElementHandler
		parser.CharacterDataHandler = self._characterDataHandler

		pos = 0
		while True:
			chunk = file.read(BUFSIZE).encode('utf-8')
			if not chunk:
				parser.Parse(chunk, 1)
				break
			pos = pos + len(chunk)
			if self.progress:
				self.progress.set(pos // 100)
			parser.Parse(chunk, 0)
	def start_element(self,name,attrs):
		print('start_element:%s,attrs:%s'%(name,str(attrs)))
		# print(type(attrs))
		# print('start_element:%s,attrs:%s'%(name,attrs))
	def end_element(self,name):
		print('end_element:%s'% name)
	def char_data(self,text):
		print('char_data:%s'% text)

xml = r'''<?xml version="1.0"?>
<ol>
    <li><a href="/python">Python</a></li>
    <li><a href="/ruby">Ruby</a></li>
</ol>
'''
xml1= r'''<?xml version="1.0"?>
<ol><li><a href="/python">Python</a></li><li><a href="/ruby">Ruby</a></li></ol>
'''
handler=defaultsaxhandler()
print(type(defaultsaxhandler))
parser=ParserCreate()#创建解释器
print(type(parser))
print('---------------------------')
parser.StartElementHandler=handler.start_element
parser.EndElementHandler=handler.end_element
parser.CharacterDataHandler=handler.char_data#CharacterDataHandler是parser内部定义的
# parser.Parse(xml)#好像每次只能parser一个;注意看一下,好像char_Data会解析处文档中间的空格
print('------------------')
parser.Parse(xml1)

예제 #32
0
class MYSAXHandler(object):
    def start_element(self,name,attrs):
        print("start element: %s,attrs:%s" % (name,attrs))
    def end_element(self,name):
        print("end element:%s" % (name))
    def char_data(slef,data):
        print("text data:%s"%data)

mysaxHandler = MYSAXHandler()
#创建parser
parser = ParserCreate()
#设置开始元素解析句柄
parser.StartElementHandler = mysaxHandler.start_element
#设置结束元素解析句柄
parser.EndElementHandler = mysaxHandler.end_element
#设置data元素解析句柄
parser.CharacterDataHandler = mysaxHandler.char_data
# 前面不能有空格或换行
xml = r'''<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#ffffff" />
    <corners
        android:bottomLeftRadius="360dp"
        android:topLeftRadius="360dp" />
    <size android:height="41dp" />
</shape>

'''
print(type(parser))
parser.Parse(xml)
예제 #33
0
        print('sax:end_element:%s' % name)

    def char_data(self, text):
        print('sax:char_data: %s' % text)


xml = r'''<?xml version="1.0"?>
<ol>
    <li><a href="/python">Python</a></li>
    <li><a href="/ruby">Ruby</a></li>
</ol>'''
handler = DefaultSaxHandler()
parser = ParserCreate()
parser.StartElementHandler = handler.start_element
parser.EndElementHandler = handler.end_element
parser.CharacterDataHandler = handler.char_data
parser.Parse(xml)
print('-----------------------------------------\n')

#urllib///////////////////////////////////////////////////
#urllib提供了一系列用于操作URL的功能。

#Get-----------------------------------------------
#urllib的request模块可以非常方便地抓取URL内容,也就是发送一个GET请求到指定的页面,然后返回HTTP的响应:
#例如,对豆瓣的一个URLhttps://api.douban.com/v2/book/2129650进行抓取,并返回响应:
from urllib import request
with request.urlopen('https://api.douban.com/v2/book/2129650') as f:
    data = f.read()
    print('Status:', f.status, f.reason)
    for k, v in f.getheaders():
        print('%s: %s' % (k, v))
예제 #34
0

class DefaultSAXHandler(object):
    def start_element(self, name, attrs):
        print("SAX:start_element: %s, attrs: %s" % (name, str(attrs)))

    def end_element(self, name):
        print("SAX:end_element: %s" % name)

    def char_data(self, text):
        print("SAX:char_data: %s" % text)


xml = r'''<?xml version="1.0"?>
<ol>
    <li><a href="/python">Python</a></li>
    <li><a href="ruby">Ruby</a></li>
</ol>
'''
# create a xml example

# parse it
handler = DefaultSAXHandler()
parser = ParserCreate()

parser.StartElementHandler = handler.start_element
parser.EndElementHandler = handler.end_element
parser.CharacterDataHandler = handler.char_data  # customize handler action

parser.Parse(xml)
예제 #35
0
 def setup_parser(self):
     parser = ParserCreate()
     parser.StartElementHandler = self.StartElementHandler
     parser.EndElementHandler = self.EndElementHandler
     parser.CharacterDataHandler = self.CharacterDataHandler
     return parser