本文整理汇总了Python中xml.etree.ElementTree.XML.findall方法的典型用法代码示例。如果您正苦于以下问题:Python XML.findall方法的具体用法?Python XML.findall怎么用?Python XML.findall使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xml.etree.ElementTree.XML
的用法示例。
在下文中一共展示了XML.findall方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: pmc_article_search
# 需要导入模块: from xml.etree.ElementTree import XML [as 别名]
# 或者: from xml.etree.ElementTree.XML import findall [as 别名]
def pmc_article_search():
id_list = []
search_string = '((neuron electrophysiology) OR (neurophysiology) OR ("input resistance") OR ("resting potential" OR "resting membrane potential") OR "LTP" OR "synaptic plasticity" OR "LTD")'
search_string_quoted = quote(search_string, safeChars)
#print search_string_quoted
retstart = 0
retmax = 20
link = esearch % (search_string_quoted, retstart, retmax)
req = Request(link)
handle = urlopen(req)
data = handle.read()
xml = XML(data)
num_found_articles = 20#int(xml.find('.//Count').text)
while retstart < num_found_articles:
link = esearch % (search_string_quoted, retstart, retmax)
req = Request(link)
handle = urlopen(req)
data = handle.read()
#print data
xml = XML(data)
id_list_temp = xml.findall(".//Id")
if len(id_list_temp) == 0:
id_list_temp = int(xml.findall(".//Id"))
for id_elem in id_list_temp:
id_list.append(int(id_elem.text))
retstart += retmax
return id_list
示例2: protocolParser
# 需要导入模块: from xml.etree.ElementTree import XML [as 别名]
# 或者: from xml.etree.ElementTree.XML import findall [as 别名]
def protocolParser(protocol,game,conn):
print protocol
xmlelement=XML(protocol)
print xmlelement.tag
if(xmlelement.tag=="CLOGIN"):
a_lst = xmlelement.findall("username")
val=''
for node in a_lst:
val=node.attrib["usr"]
print val
threading.Thread(target=srvau(val,game,conn)).start()
elif(xmlelement.tag=="CPLAY"):
a_lst = xmlelement.findall("username")
print 'a_lst'
val=''
for node in a_lst:
val=node.attrib["usr"]
print val
threading.Thread(target=splay(val,game,conn)).start()
elif(xmlelement.tag=="CDICE"):
a_lst = xmlelement.findall("username")
val=''
for node in a_lst:
val=node.attrib["usr"]
print val
threading.Thread(target=sdice(val,game,conn)).start()
示例3: _get_sys_info
# 需要导入模块: from xml.etree.ElementTree import XML [as 别名]
# 或者: from xml.etree.ElementTree.XML import findall [as 别名]
def _get_sys_info(self):
"""
Returns sysinfo of host system in the following format::
{'memory': [{'bank_locator': 'BANK 0',
'form_factor': 'SODIMM',
'locator': 'ChannelA-DIMM0',
'manufacturer': 'Samsung',
'part_number': 'M471B5273DH0-CK0',
'serial_number': '9760E90B',
'size': '4096 MB',
'speed': '1600 MHz',
'type': 'DDR3',
'type_detail': 'Synchronous'},
{'bank_locator': 'BANK 2',
'form_factor': 'SODIMM',
'locator': 'ChannelB-DIMM0',
'manufacturer': 'Micron',
'part_number': '16KTF51264HZ-1G6M1',
'serial_number': '3255C613',
'size': '4096 MB',
'speed': '1600 MHz',
'type': 'DDR3',
'type_detail': 'Synchronous'}],
'processor': {'external_clock': '100 MHz',
'family': 'Core i5',
'manufacturer': 'Intel(R) Corporation',
'max_speed': '2600 MHz',
'part_number': 'None',
'serial_number': 'None',
'signature': 'Type 0, Family 6, Model 58, Stepping 9',
'socket_destination': 'CPU Socket - U3E1',
'status': 'Populated, Enabled',
'type': 'Central Processor',
'version': 'Intel(R) Core(TM) i5-3320M CPU @ 2.60GHz'},
'system': {'family': 'ThinkPad T430',
'manufacturer': 'LENOVO',
'product': '234455G',
'serial': 'PBKVYA6',
'sku': 'LENOVO_MT_2344',
'uuid': 'D6A27701-51F5-11CB-963F-F8A34AA11505',
'version': 'ThinkPad T430'}}
"""
xml = XML(self.conn.getSysinfo(0))
sysinfo = {}
keys = ['system', 'processor']
for key in keys:
sysinfo[key] = {}
for element in xml.findall(key+'/entry'):
sysinfo[key][element.attrib['name']] = element.text
sysinfo['memory'] = []
for memorydevs in xml.findall('memory_device'):
x = {}
for entry in memorydevs.findall('entry'):
x[entry.attrib['name']] = entry.text
sysinfo['memory'].append(x)
return sysinfo
示例4: pubmed_count_coauthored_papers
# 需要导入模块: from xml.etree.ElementTree import XML [as 别名]
# 或者: from xml.etree.ElementTree.XML import findall [as 别名]
def pubmed_count_coauthored_papers(author_1, author_2):
"""
Count number of co-published papers between author_1 and author_2
co-published defined by number of papers in pubmed where author_1 is
first author and author_2 is last author
Args:
author_1 (str): String of first authors name; e.g., Tripathy S
author_2 (str): String of second authors name; e.g., Urban N
Returns:
match_count (int): count of numbers of matching pubmed articles
"""
advisee_author_str = author_1
adviser_author_str = author_2
esearchlink = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?'+\
'db=pubmed&term=%s[Author] AND (%s[Author])'
efetch = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?'+\
'&db=pubmed&retmode=xml&id=%s'
advisee_last_name = advisee_author_str.split()[0]
#print advisee_last_name
adviser_last_name = adviser_author_str.split()[0]
match_count = 0
link = esearchlink % (advisee_author_str, adviser_author_str)
linkCoded = quote(link, ':=/&()?_')
req = Request(linkCoded)
handle = urlopen(req)
data = handle.read()
xml = XML(data)
matching_pmids = [xml_ob.text for xml_ob in xml.findall('.//Id')]
for pmid in matching_pmids:
link = efetch % (pmid)
req = Request(link)
handle = urlopen(req)
data = handle.read()
xml = XML(data)
authorList = xml.findall(".//Author[@ValidYN='Y']")
if len(authorList) == 0:
authorList = xml.findall(".//Author")
#print authorList
if len(authorList) > 1:
#print data
try:
first_author_last_name = authorList[0].find("./LastName").text
#print first_author_last_name
last_author_last_name = authorList[-1].find("./LastName").text
except Exception:
continue
if first_author_last_name == advisee_last_name and last_author_last_name == adviser_last_name:
match_count += 1
#print '%s, %s, matching pubs = %d' % \
# (advisee_author_str, adviser_author_str, match_count)
return match_count
示例5: _list_alchemy_results
# 需要导入模块: from xml.etree.ElementTree import XML [as 别名]
# 或者: from xml.etree.ElementTree.XML import findall [as 别名]
def _list_alchemy_results(xml, relevance):
dom = XML(xml)
results = []
if dom.find("status").text == "OK":
for concept in dom.findall(".//concept"):
if float(concept.find("relevance").text) > relevance:
results.append(concept.find("text").text)
for kw in dom.findall(".//keyword"):
if float(kw.find("relevance").text) > relevance:
results.append(kw.find("text").text)
return results
示例6: parse
# 需要导入模块: from xml.etree.ElementTree import XML [as 别名]
# 或者: from xml.etree.ElementTree.XML import findall [as 别名]
def parse(self,url):
ti = TextInventory()
logger.info("Parsing CTS service @ %s"%url)
try:
# TODO: separate this line in order to raise separate errors!
xml_ti = XML(urllib2.urlopen(url+_get_capab_req).read())
# retrieve and store the TI version
for node in xml_ti.findall('.//%sTextInventory'%_cts_ns):
ti.set_version(node.attrib.get('tiversion'))
logger.info("TextInventory version: %s"%ti.get_version())
# retrieve and store the textgroups
for node in xml_ti.findall('.//%stextgroup'%_cts_ns):
tg = TextGroup(id=node.attrib.get('projid'))
tg.xml = ElementTree.tostring(node)
ti.add('tg',tg)
# retrieve and store the works
for child in node:
# parse groupname elem
if(child.tag=="%s%s"%(_cts_ns,"groupname")):
tg.set_name(child.attrib.get("%slang"%_xml_ns),re.sub(r'\s\s+',"",child.text))
logger.debug("Found TextGroup: \"%s\""%tg.get_name(child.attrib.get("%slang"%_xml_ns)))
#parse work elem
elif(child.tag=="%s%s"%(_cts_ns,"work")):
w = Work(id=child.attrib.get('projid'),tg=tg.id)
for title in child.findall('.//%stitle'%_cts_ns):
w.set_title(title.text)
ti.add('wk',w)
logger.debug("Found Work: %s"%w.id)
# parse edition elem
for node in child.findall('.//%sedition'%_cts_ns):
e = Edition(id=node.attrib.get('projid'),work=w.id)
for child in node:
if(child.tag=="%s%s"%(_cts_ns,"label")):
e.label=child.text
elif(child.tag=="%s%s"%(_cts_ns,"description")):
lang=child.attrib.get("%slang"%_xml_ns)
desc=child.text
e.add_desc(lang,desc)
elif(child.tag=="%s%s"%(_cts_ns,"online")):
pass
#
ti.add('ed',e)
except ExpatError as error:
logger.error("Parsing of %s failed with error \"%s\""%(url,str(error)))
return ti
示例7: __init__
# 需要导入模块: from xml.etree.ElementTree import XML [as 别名]
# 或者: from xml.etree.ElementTree.XML import findall [as 别名]
def __init__(self, **kwargs):
self._issue_date_utc = None
self._expiration_date_utc = None
self.is_trial = "false"
if "xml_node" in kwargs:
xml_node = kwargs["xml_node"]
else:
xml_node = XML(kwargs["xml"])
xml_attrs = xml_node.attrib
attrs = {
"id": "licenseId",
"user_id": "userId",
"payment_plan_id": "paymentPlanId",
"issue_date_utc": "issueDateUTC",
"expiration_date_utc": "expirationDateUTC",
"is_trial": "is_trial",
}
for k, v in attrs.items():
if v in xml_attrs:
setattr(self, k, xml_attrs[v])
else:
setattr(self, k, None)
features = []
for node in xml_node.findall(".//feature"):
feature = Feature(xml_node=node)
features.append(feature)
self.features = features
super().__init__(**kwargs)
示例8: load
# 需要导入模块: from xml.etree.ElementTree import XML [as 别名]
# 或者: from xml.etree.ElementTree.XML import findall [as 别名]
def load(text, match=None):
"""This function reads a string that contains the XML of an Atom Feed, then
returns the
data in a native Python structure (a ``dict`` or ``list``). If you also
provide a tag name or path to match, only the matching sub-elements are
loaded.
:param text: The XML text to load.
:type text: ``string``
:param match: A tag name or path to match (optional).
:type match: ``string``
"""
if text is None: return None
text = text.strip()
if len(text) == 0: return None
nametable = {
'namespaces': [],
'names': {}
}
root = XML(text)
items = [root] if match is None else root.findall(match)
count = len(items)
if count == 0:
return None
elif count == 1:
return load_root(items[0], nametable)
else:
return [load_root(item, nametable) for item in items]
示例9: download
# 需要导入模块: from xml.etree.ElementTree import XML [as 别名]
# 或者: from xml.etree.ElementTree.XML import findall [as 别名]
def download(job, regex):
"""Grabs platform specific distribution targets from Hudson"""
url = urllib.urlopen("/".join([HUDSON_ROOT, job, HUDSON_XML_SUFFIX]))
hudson_xml = url.read()
hudson_xml = hudson_xml.replace('origin/', 'origin_')
url.close()
root = XML(hudson_xml)
building = root.findtext("./building")
if building == 'true':
print '%s build in progress, exiting...' % job
sys.exit(1)
revision = root.findtext("./changeSet/revision/revision")
artifacts = root.findall("./artifact")
print "Retrieving %s job artifacts from revision: %s" % (job, revision)
base_url = "/".join([HUDSON_ROOT, job, 'lastSuccessfulBuild/artifact'])
new_artifacts = list()
for artifact in artifacts:
filename = artifact.findtext("fileName")
if not regex.match(filename):
continue
artifact_url = "/".join([base_url, artifact.findtext("relativePath")])
print "Downloading %s from URL %s" % (filename, artifact_url)
urllib.urlretrieve(artifact_url , filename)
new_artifacts.append(filename)
return [revision, new_artifacts]
示例10: updated
# 需要导入模块: from xml.etree.ElementTree import XML [as 别名]
# 或者: from xml.etree.ElementTree.XML import findall [as 别名]
def updated(downloader, path, _):
if path is None:
logging.error('internet archive file list get fail')
# FIXME: report to user a failure to download
return
from xml.etree.ElementTree import XML
xml = XML(open(path, 'r').read())
os.remove(path)
table = {
'text pdf': u'application/pdf',
'grayscale luratech pdf': u'application/pdf-bw',
'image container pdf': u'application/pdf',
'djvu': u'image/x.djvu',
'epub': u'application/epub+zip',
}
chosen = None
for element in xml.findall('file'):
fmt = element.find('format').text.lower()
if fmt in table:
if table[fmt] == content_type:
chosen = element.get('name')
break
if chosen is None:
logging.error('internet archive file list omits content type')
# FIXME: report to user a failure to find matching content
return
url = os.path.join(url_base, chosen)
GObject.idle_add(download_cb, url)
示例11: gsversion
# 需要导入模块: from xml.etree.ElementTree import XML [as 别名]
# 或者: from xml.etree.ElementTree.XML import findall [as 别名]
def gsversion(self):
'''obtain the version or just 2.2.x if < 2.3.x
Raises:
FailedRequestError: If the request fails.
'''
if self._version: return self._version
about_url = self.service_url + "/about/version.xml"
response, content = self.http.request(about_url, "GET")
version = None
if response.status == 200:
dom = XML(content)
resources = dom.findall("resource")
for resource in resources:
if resource.attrib["name"] == "GeoServer":
try:
version = resource.find("Version").text
break
except:
pass
#This will raise an exception if the catalog is not available
#If the catalog is available but could not return version information,
#it is an old version that does not support that
if version is None:
self.get_workspaces()
# just to inform that version < 2.3.x
version = "2.2.x"
self._version = version
return version
示例12: get_pubmed_id_from_doi
# 需要导入模块: from xml.etree.ElementTree import XML [as 别名]
# 或者: from xml.etree.ElementTree.XML import findall [as 别名]
def get_pubmed_id_from_doi(doi):
searchLink = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term=%s[aid]" % (doi)
handle = urlopen(searchLink)
data = handle.read()
xml = XML(data) # convert to an xml object so we can apply x-path search fxns to it
pmidList = [x.text for x in xml.findall(".//Id")] # find xml "Id" elements
return pmidList
示例13: __init__
# 需要导入模块: from xml.etree.ElementTree import XML [as 别名]
# 或者: from xml.etree.ElementTree.XML import findall [as 别名]
def __init__(self, args):
self.args = args
url = opener.open(args.build+"api/xml")
try:
log.debug('Fetching xml from %s code:%d', url.url, url.code)
if url.code != 200:
log.error('Failed to get CI XML from %s (code %d)',
url.url, url.code)
raise Stop(20, 'Job lookup failed, is the job name correct?')
ci_xml = url.read()
finally:
url.close()
root = XML(ci_xml)
artifacts = root.findall("./artifact")
base_url = args.build+"artifact/"
if len(artifacts) <= 0:
raise AttributeError(
"No artifacts, please check build on the CI server.")
patterns = self.get_artifacts_list()
for artifact in artifacts:
filename = artifact.find("fileName").text
for key, value in patterns.iteritems():
if re.compile(value).match(filename):
rel_path = base_url + artifact.find("relativePath").text
setattr(self, key, rel_path)
pass
示例14: identify
# 需要导入模块: from xml.etree.ElementTree import XML [as 别名]
# 或者: from xml.etree.ElementTree.XML import findall [as 别名]
def identify(self, geosGeometry, geometryFieldName, layers, url, username, password):
"""
Assuming :
Url like http://localhost:8080/geoserver/wfs
layers like geonode:capa
geosGeometry is in Lambert72
"""
#TODO input checking
gmlString = geosGeometry.ogr.gml
payload = self._buildWfsIntersectRequest(gmlString, layers, geometryFieldName)
#Verify False to avoid certificate not trusted problems
r = requests.post(url, data = payload, auth=(username, password), verify=False)
tree = XML(r.text)
if tree.tag == "{http://www.opengis.net/ogc}ServiceExceptionReport":
#We Got OGC Error. Find the root cause and throw a proper Exception
se = tree.find('{http://www.opengis.net/ogc}ServiceException')
raise Exception(str(se.text).strip())
else:
clean_results = []
features = tree.findall('{http://www.opengis.net/gml}featureMember')
for feature in features:
attributes = {}
for child in feature:
for child_elem in child:
tag_name = child_elem.tag.split('}')[-1] #Get rid of namespace
if child_elem.text is not None:
attributes[tag_name] = child_elem.text
else:
attributes[tag_name] = ""
clean_results.append(attributes)
return clean_results
示例15: findSha1Artifacts
# 需要导入模块: from xml.etree.ElementTree import XML [as 别名]
# 或者: from xml.etree.ElementTree.XML import findall [as 别名]
def findSha1Artifacts(self, strFileName, strGroupID, strArtifactID):
atVersions = []
# Generate the SHA1 sum for the file.
strFileSha1 = self.generate_sha1_from_file(strFileName)
strPath = self.strUrlLuceneSearchSha1 % strFileSha1
aucContent = self.tRestDriver.get(self.tServerBaseUrl, strPath)
tSearchResult = XML(aucContent)
# The search result must be complete.
if tSearchResult.findtext('tooManyResults')!='false':
raise Exception("Received a truncated search result!")
# Loop over all results.
for tNode in tSearchResult.findall('data/artifact'):
strG = tNode.findtext('groupId')
strA = tNode.findtext('artifactId')
strVersion = tNode.findtext('version')
if isinstance(strG, basestring)==True and isinstance(strA, basestring)==True and isinstance(strVersion, basestring)==True:
strG = strG.strip()
strA = strA.strip()
strVersion = strVersion.strip()
if strGroupID==strG and strArtifactID==strA:
if strVersion=='SNAPSHOT':
tVersion = deploy_version.version(0, 0, 0)
else:
tVersion = deploy_version.version(strVersion)
atVersions.append(tVersion)
atVersions.sort()
return atVersions