当前位置: 首页>>代码示例>>Python>>正文


Python XML.find方法代码示例

本文整理汇总了Python中xml.etree.cElementTree.XML.find方法的典型用法代码示例。如果您正苦于以下问题:Python XML.find方法的具体用法?Python XML.find怎么用?Python XML.find使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在xml.etree.cElementTree.XML的用法示例。


在下文中一共展示了XML.find方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: fix_etree

# 需要导入模块: from xml.etree.cElementTree import XML [as 别名]
# 或者: from xml.etree.cElementTree.XML import find [as 别名]
def fix_etree():
    try:
        from xml.etree.cElementTree import XML
        e = XML('<test><t a="1"/></test>')
        e.find('t[@a="1"]')
    except SyntaxError:
        import canari.xmltools.fixetree
开发者ID:mattnewham,项目名称:canari,代码行数:9,代码来源:common.py

示例2: parse_auth

# 需要导入模块: from xml.etree.cElementTree import XML [as 别名]
# 或者: from xml.etree.cElementTree.XML import find [as 别名]
def parse_auth(soup, iview_config):
	"""	There are lots of goodies in the auth handshake we get back,
		but the only ones we are interested in are the RTMP URL, the auth
		token, and whether the connection is unmetered.
	"""

	xml = XML(soup)
	xmlns = "http://www.abc.net.au/iView/Services/iViewHandshaker"

	# should look like "rtmp://203.18.195.10/ondemand"
	rtmp_url = xml.find('{%s}server' % (xmlns,)).text

	# at time of writing, either 'Akamai' (usually metered) or 'Hostworks' (usually unmetered)
	stream_host = xml.find('{%s}host' % (xmlns,)).text

	if stream_host == 'Akamai':
		playpath_prefix = config.akamai_playpath_prefix
	else:
		playpath_prefix = ''

	if rtmp_url is not None:
		# Being directed to a custom streaming server (i.e. for unmetered services).
		# Currently this includes Hostworks for all unmetered ISPs except iiNet.

		rtmp_chunks = rtmp_url.split('/')
		rtmp_host = rtmp_chunks[2]
		rtmp_app = rtmp_chunks[3]
	else:
		# We are a bland generic ISP using Akamai, or we are iiNet.
		rtmp_url  = iview_config['rtmp_url']
		rtmp_host = iview_config['rtmp_host']
		rtmp_app  = iview_config['rtmp_app']

	token = xml.find("{%s}token" % (xmlns,)).text

	return {
		'rtmp_url'        : rtmp_url,
		'rtmp_host'       : rtmp_host,
		'rtmp_app'        : rtmp_app,
		'playpath_prefix' : playpath_prefix,
		'token'           : token,
		'free'            :
			(xml.find("{%s}free" % (xmlns,)).text == "yes")
	}
开发者ID:bencollerson,项目名称:python-iview,代码行数:46,代码来源:parser.py

示例3: LayoutBuilder

# 需要导入模块: from xml.etree.cElementTree import XML [as 别名]
# 或者: from xml.etree.cElementTree.XML import find [as 别名]
class LayoutBuilder():
    def __init__(self, im,  pl):
        self.im = im
        self.pl = pl
        self.plugins = {}
        self.trb = TextRendererBuilder()
        
    def build(self, xml, parent):
        self.tree = XML(self._surround(xml))
        self._readPlugins(self.tree.find("plugins"))
        return self._readBody(self.tree.find("body"),  parent)
            
    def _buildLine(self, element,  parent):
        line = QGraphicsLinearLayout(Qt.Horizontal, parent)
        for e in element:
            line.addItem(self._buildLabel(e))
        return line
            
    def _buildLabel(self, element):
        item = self.im.getItemByName(element.tag)
        plugin = self.plugins[element.get('parser')]
        return self.trb.build(item, plugin, element.text, element.get("align"))
        
    def _readPlugins(self,  xml):
        for element in xml:
            plugin = self.pl.getPluginByName(element.tag)
            self.plugins[element.get("name")] = plugin
            optionKeys = element.keys()
            optionKeys.remove("name")
            options = {}
            for key in optionKeys:
                options[key] = element.get(key)
            plugin.load(options)
            
    def _readBody(self,  xml,  parent):
        layout = QGraphicsLinearLayout(Qt.Vertical, parent)
        for element in xml.getiterator("line"):
            print "parsing line"
            layout.addItem(self._buildLine(element,  layout))
        return layout
        
    def _surround(self,  xml):
        print xml
        return "<all>" + xml + "</all>"
开发者ID:tcoopman,项目名称:bloated-clock-plasmoid,代码行数:46,代码来源:layout.py

示例4: fetch

# 需要导入模块: from xml.etree.cElementTree import XML [as 别名]
# 或者: from xml.etree.cElementTree.XML import find [as 别名]
def fetch(*pos, dest_file, quiet=False, frontend=None, abort=None, **kw):
    url = manifest_url(*pos, **kw)
    if not quiet:
        print(url, file=stderr)
    
    with PersistentConnectionHandler() as connection:
        session = urllib.request.build_opener(connection)
        
        with session.open(url) as response:
            manifest = response.read()
        
        manifest = XML(manifest)
        # TODO: this should be determined from bootstrap info presumably
        (frags, _) = manifest.findtext(F4M_NAMESPACE + "duration").split(".")
        frags = (int(frags) + 2) // 3
        
        # TODO: determine preferred bitrate, max bitrate, etc
        media = manifest.find(F4M_NAMESPACE + "media")  # Just pick the first one!
        
        player = player_verification(manifest)
        if not quiet:
            print(player, file=stderr)
        media_url = media.get("url")
        metadata = media.findtext(F4M_NAMESPACE + "metadata")
        metadata = b64decode(metadata.encode("ascii"), validate=True)
        with open(dest_file, "wb") as flv:
            flv.write(bytes.fromhex("464C560105000000090000000012"))
            flv.write(len(metadata).to_bytes(3, "big"))
            flv.write(bytes(3 + 4))
            flv.write(metadata)
            flv.write(bytes.fromhex("00019209"))
            
            for frag in range(frags):
                frag += 1
                frag_url = "{}Seg1-Frag{}?{}".format(media_url, frag, player)
                frag_url = urljoin(url, frag_url)
                
                try:
                    response = session.open(frag_url)
                except HTTPError as err:
                    if err.code != http.client.NOT_FOUND:
                        raise
                    # Relying on requests for fragments after the final
                    # fragment to return 404 "Not found" errors
                    break
                
                while True:
                    boxsize = response.read(4)
                    if not boxsize:
                        break
                    boxtype = response.read(4)
                    assert len(boxsize) == 4 and len(boxtype) == 4
                    boxsize = int.from_bytes(boxsize, "big")
                    if boxsize == 1:
                        boxsize = response.read(8)
                        assert len(boxsize) == 8
                        boxsize = int.from_bytes(boxsize, "big")
                        boxsize -= 16
                    else:
                        boxsize -= 8
                    assert boxsize >= 0
                    
                    if boxtype == b"mdat":
                        if frag > 1:
                            for _ in range(2):
                                streamcopy(response, null_writer, 1,
                                    abort=abort)
                                packetsize = response.read(3)
                                assert len(packetsize) == 3
                                packetsize = int.from_bytes(packetsize, "big")
                                packetsize += 11 + 4
                                streamcopy(response, null_writer,
                                    packetsize - 4, abort=abort)
                                boxsize -= packetsize
                                assert boxsize >= 0
                        streamcopy(response, flv, boxsize, abort=abort)
                    else:
                        streamcopy(response, null_writer, boxsize,
                            abort=abort)
                
                size = flv.tell()
                if frontend:
                    frontend.set_size(size)
                else:
                    stderr.write("\rFrag {}; {:.1F} MB\r".format(frag, size / 1e6))
                    stderr.flush()
            else:
                if not frontend:
                    print(file=stderr)
                msg = "Fragment number would exceeded {}".format(frags)
                raise NotImplementedError(msg)
            if not frontend:
                print(file=stderr)
开发者ID:feldegast,项目名称:python-iview,代码行数:95,代码来源:hds.py

示例5: NmapReportParser

# 需要导入模块: from xml.etree.cElementTree import XML [as 别名]
# 或者: from xml.etree.cElementTree.XML import find [as 别名]
class NmapReportParser(object):

    def __init__(self, output):
        self.output = output
        self.xml = XML(output)

    def os(self, address):
        host = self._host(address)
        if host is not None:
            r = {
                'osmatch': [osm.attrib for osm in host.findall('os/osmatch')],
                'osclass': [osm.attrib for osm in host.findall('os/osclass')],
                'portused': host.find('os/portused').attrib
            }
            return r
        return { 'osmatch' : [], 'osclass' : [], 'portused' : {} }

    @property
    def addresses(self):
        return [ a.get('addr') for a in self.xml.findall('host/address') if a.get('addrtype') == 'ipv4' ]

    @property
    def report(self):
        return self.output

    def mac(self, address):
        host = self._host(address)
        if host is not None:
            for addr in host.findall('address'):
                if addr.get('addrtype') == 'mac':
                    return addr.get('addr')
        return None

    def _host(self, address):
        for host in self.xml.findall('host'):
            for addr in host.findall('address'):
                if addr.get('addr') == address:
                    return host
        return None

    def ports(self, address):
        host = self._host(address)
        ports = []
        if host is not None:
            for p in host.findall('ports/port'):
                r = p.attrib
                map(lambda x: r.update(x.attrib), p.getchildren())
                ports.append(r)
        return ports

    @property
    def scaninfo(self):
        return self.xml.find('scaninfo').attrib

    @property
    def verbosity(self):
        return self.xml.find('verbose').get('level')

    @property
    def debugging(self):
        return self.xml.find('debugging').get('level')

    def hostnames(self, address):
        host = self._host(address)
        if host is not None:
            return [ hn.attrib for hn in host.findall('hostnames/hostname') ]
        return []

    def times(self, address):
        host = self._host(address)
        if host is not None:
            return host.find('times').attrib
        return {}

    @property
    def runstats(self):
        rs = {}
        map(lambda x: rs.update(x.attrib), self.xml.find('runstats').getchildren())
        return rs

    def scanstats(self, address):
        host = self._host(address)
        if host is not None:
            return host.attrib
        return {}

    def status(self, address):
        host = self._host(address)
        if host is not None:
            return host.find('status').attrib
        return {}

    @property
    def nmaprun(self):
        return self.xml.attrib

    def tobanner(self, port):
        banner = port.get('product', 'Unknown')
        version = port.get('version')
        if version is not None:
#.........这里部分代码省略.........
开发者ID:mshelton,项目名称:sploitego,代码行数:103,代码来源:nmap.py

示例6: xml_to_atom

# 需要导入模块: from xml.etree.cElementTree import XML [as 别名]
# 或者: from xml.etree.cElementTree.XML import find [as 别名]
def xml_to_atom(xml,feedtitle,feeddescription,feedurl,authoremail,img_size=0):
  """Transform the XML from Tumblr into an Atom feed.
  
  :param string xml: Raw XML returned from Tumblr
  :param string feedtitle: Title of the atom feed
  :param string feeddescription: Description of the atom feed
  :param string feedurl: URL that will contain the feed
  :param int img_size: Size of images to include; 0-5 (0 is original, 5 is small)
  :returns: The Atom feed's XML
  """
  # Make sure parameters are "good"
  if feedurl.endswith('atom.xml'):
    pass
  elif feedurl[-1] == '/':
    feedurl = feedurl+'atom.xml'
  else:
    feedurl = feedurl+'/atom.xml'
  
  if type(img_size) is not int:
    img_size = int(img_size)
  
  # Set up the Atom feed
  atom = Feed()
  atom.feed["title"] = feedtitle
  atom.feed["description"] = feeddescription
  atom.feed["id"] = feedurl
  atom.feed["link"] = {'_href': feedurl,
                       '_rel': 'self',
                       '_type': 'application/atom+xml'}
  atom.feed["generator"] = {'_uri': "http://github.com/tbekolay/Tumblr-Dashboard-Feed",
                            '_version': '0.1',
                            'text': 'Tumblr Dashboard Reader'}
  atom.feed["icon"] = "http://assets.tumblr.com/images/favicon.gif"
  atom.feed["logo"] = "http://assets.tumblr.com/images/logo.png"
  atom.feed["author"] = {'name':authoremail.split('@')[0], 'email':authoremail}
  atom.feed["updated"] = time.gmtime()
  
  # Start parsing the XML file
  et = XML(xml)
  posts = et.find('posts')
  
  for post in posts.findall('post'):
    # Information common to all types
    item = {}
    item["id"] = post.attrib.get('url-with-slug')
    item["link"] = {'_href': post.attrib.get('url-with-slug'),
                    '_rel': 'alternate',
                    '_type': 'text/html'}
    date = time.strptime(post.attrib.get('date-gmt'),"%Y-%m-%d %H:%M:%S %Z") #2011-09-12 00:33:28 GMT
    item["published"] = date
    item["updated"] = date
    author = post.find('tumblelog')
    shortname = author.attrib.get('name')
    item["author"] = {'name': author.attrib.get('title')+" ("+shortname+")",
                      'uri': author.attrib.get('url')}
    posttype = post.attrib.get('type')
    
    # Make the summary, based on type
    if posttype == "regular":
      item["summary"] = shortname+" posted on Tumblr"
    elif posttype == "answer":
      item["summary"] = shortname+" posted an "+posttype
    elif posttype == "audio":
      item["summary"] = shortname+" posted "+posttype
    else:
      item["summary"] = shortname+" posted a "+posttype
    
    # Get title and content based on type
    content = StringIO()
    #### regular ####
    if posttype == "regular":
      if post.find('regular-title') is None:
        item["title"] = item["summary"]
      else:
        item["title"] = post.find('regular-title').text
      
      if post.find('regular-body') is None:
        content.write(item["title"])
        item["title"] = item["summary"]
      else:
        content.write(post.find('regular-body').text)
    #### link ####
    elif posttype == "link":
      item["title"] = item["summary"]
      
      if post.find('link-title') is None:
        title = post.find('link-url').text
      else:
        title = post.find('link-text').text
      
      if post.find('link-description') is None:
        description = "<p>(No description)</p>"
      else:
        description = post.find('link-description').text
      
      content.write('<a href="%(url)s">%(title)s</a>:%(description)s' % \
                    {'url':post.find('link-url').text,
                     'title':title,
                     'description':description})
    #### quote  ####
#.........这里部分代码省略.........
开发者ID:tbekolay,项目名称:Tumblr-Dashboard-Feed,代码行数:103,代码来源:tumblr-dashboard-feed.py


注:本文中的xml.etree.cElementTree.XML.find方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。