python etree xpath_Python etree.XPath方法代码示例

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

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

示例1: post

​点赞 6

# 需要导入模块: from lxml import etree [as 别名]

# 或者: from lxml.etree import XPath [as 别名]

def post(self, html):

"""

Try to play with request ...

"""

import urllib2

response = urllib2.urlopen('file://%s' % html)

data = response.read()

post = etree.HTML(data)

# find text function

find_text = etree.XPath("//text()", smart_strings=False)

LOG.info(find_text(post))

post.clear()

开发者ID:gramps-project,项目名称:addons-source,代码行数:21,

示例2: test_parse_rule

​点赞 6

# 需要导入模块: from lxml import etree [as 别名]

# 或者: from lxml.etree import XPath [as 别名]

def test_parse_rule():

"""Ensure parse_rule returns expected output."""

expr = XPath("//Num")

assert parse_rule(

rule_name='',

rule_values=dict(

description='',

expr=expr,

example="a = 1",

instead="a = int('1')",

settings=Settings(included=[], excluded=[], allow_ignore=True),

)

) == Rule(

name='',

description='',

expr=expr,

example="a = 1",

instead="a = int('1')",

settings=Settings(included=[], excluded=[], allow_ignore=True)

)

开发者ID:hchasestevens,项目名称:bellybutton,代码行数:22,

示例3: _details_prepare_merge

​点赞 6

# 需要导入模块: from lxml import etree [as 别名]

# 或者: from lxml.etree import XPath [as 别名]

def _details_prepare_merge(details):

# We may mutate the details later, so copy now to prevent

# affecting the caller's data.

details = details.copy()

# Prepare an nsmap in an OrderedDict. This ensures that lxml

# serializes namespace declarations in a stable order.

nsmap = OrderedDict((ns, ns) for ns in sorted(details))

# Root everything in a namespace-less element. Setting the nsmap

# here ensures that prefixes are preserved when dumping later.

# This element will be replaced by the root of the lshw detail.

# However, if there is no lshw detail, this root element shares

# its tag with the tag of an lshw XML tree, so that XPath

# expressions written with the lshw tree in mind will still work

# without it, e.g. "/list//{lldp}something".

root = etree.Element("list", nsmap=nsmap)

# We have copied details, and root is new.

return details, root

开发者ID:maas,项目名称:maas,代码行数:22,

示例4: _details_do_merge

​点赞 6

# 需要导入模块: from lxml import etree [as 别名]

# 或者: from lxml.etree import XPath [as 别名]

def _details_do_merge(details, root):

# Merge the remaining details into the composite document.

for namespace in sorted(details):

xmldata = details[namespace]

if xmldata is not None:

try:

detail = etree.fromstring(xmldata)

except etree.XMLSyntaxError as e:

maaslog.warning("Invalid %s details: %s", namespace, e)

else:

# Add the namespace to all unqualified elements.

for elem in detail.iter("{}*"):

elem.tag = etree.QName(namespace, elem.tag)

root.append(detail)

# Re-home `root` in a new tree. This ensures that XPath

# expressions like "/some-tag" work correctly. Without this, when

# there's well-formed lshw data -- see the backward-compatibilty

# hack futher up -- expressions would be evaluated from the first

# root created in this function, even though that root is now the

# parent of the current `root`.

return etree.ElementTree(root)

开发者ID:maas,项目名称:maas,代码行数:24,

示例5: merge_details_cleanly

​点赞 6

# 需要导入模块: from lxml import etree [as 别名]

# 或者: from lxml.etree import XPath [as 别名]

def merge_details_cleanly(details):

"""Merge node details into a single XML document.

`details` should be of the form::

{"name": xml-as-bytes, "name2": xml-as-bytes, ...}

where `name` is the namespace (and prefix) where each detail's XML

should be placed in the composite document; elements in each

detail document without a namespace are moved into that namespace.

This is similar to `merge_details`, but the ``lshw`` detail is not

treated specially. The result of this function is not compatible

with XPath expressions created for old releases of MAAS.

The returned document is always rooted with a ``list`` element.

"""

details, root = _details_prepare_merge(details)

return _details_do_merge(details, root)

开发者ID:maas,项目名称:maas,代码行数:21,

示例6: match_xpath

​点赞 6

# 需要导入模块: from lxml import etree [as 别名]

# 或者: from lxml.etree import XPath [as 别名]

def match_xpath(xpath, doc):

"""Return a match of expression `xpath` against document `doc`.

:type xpath: Either `unicode` or `etree.XPath`

:type doc: Either `etree._ElementTree` or `etree.XPathDocumentEvaluator`

:rtype: bool

"""

is_xpath_compiled = is_compiled_xpath(xpath)

is_doc_compiled = is_compiled_doc(doc)

if is_xpath_compiled and is_doc_compiled:

return doc(xpath.path)

elif is_xpath_compiled:

return xpath(doc)

elif is_doc_compiled:

return doc(xpath)

else:

return doc.xpath(xpath)

开发者ID:maas,项目名称:maas,代码行数:21,

示例7: try_match_xpath

​点赞 6

# 需要导入模块: from lxml import etree [as 别名]

# 或者: from lxml.etree import XPath [as 别名]

def try_match_xpath(xpath, doc, logger=logging):

"""See if the XPath expression matches the given XML document.

Invalid XPath expressions are logged, and are returned as a

non-match.

:type xpath: Either `unicode` or `etree.XPath`

:type doc: Either `etree._ElementTree` or `etree.XPathDocumentEvaluator`

:rtype: bool

"""

try:

# Evaluating an XPath expression against a document with LXML

# can return a list or a string, and perhaps other types.

# Casting the return value into a boolean context appears to

# be the most reliable way of detecting a match.

return bool(match_xpath(xpath, doc))

except etree.XPathEvalError as error:

# Get a plaintext version of `xpath`.

expr = xpath.path if is_compiled_xpath(xpath) else xpath

logger.warning("Invalid expression '%s': %s", expr, str(error))

return False

开发者ID:maas,项目名称:maas,代码行数:24,

示例8: scenario

​点赞 6

# 需要导入模块: from lxml import etree [as 别名]

# 或者: from lxml.etree import XPath [as 别名]

def scenario(name, xpath, doc, expected_result, expected_log=""):

"""Return a scenario (for `testscenarios`) to test `try_match_xpath`.

This is a convenience function to reduce the amount of

boilerplate when constructing `scenarios_inputs` later on.

The scenario it constructs defines an XML document, and XPath

expression, the expectation as to whether it will match or

not, and the expected log output.

"""

doc = etree.fromstring(doc).getroottree()

return (

name,

dict(

xpath=xpath,

doc=doc,

expected_result=expected_result,

expected_log=dedent(expected_log),

),

)

# Exercise try_match_xpath with a variety of different inputs.

开发者ID:maas,项目名称:maas,代码行数:24,

示例9: populate_tag_for_multiple_nodes

​点赞 6

# 需要导入模块: from lxml import etree [as 别名]

# 或者: from lxml.etree import XPath [as 别名]

def populate_tag_for_multiple_nodes(tag, nodes, batch_size=DEFAULT_BATCH_SIZE):

"""Reevaluate a single tag for a multiple nodes.

Presumably this tag's expression has recently changed. Use `populate_tags`

when many nodes need reevaluating AND there are rack controllers available

to which to farm-out work. Use this only when many nodes need reevaluating

locally, i.e. when there are no rack controllers connected.

"""

# Same expression, multuple documents: compile expression with XPath.

xpath = etree.XPath(tag.definition, namespaces=tag_nsmap)

# The XML details documents can be large so work in batches.

for batch in gen_batches(nodes, batch_size):

probed_details = get_probed_details(batch)

probed_details_docs_by_node = {

node: merge_details(probed_details[node.system_id])

for node in batch

}

nodes_matching, nodes_nonmatching = classify(

partial(try_match_xpath, xpath, logger=maaslog),

probed_details_docs_by_node.items(),

)

tag.node_set.remove(*nodes_nonmatching)

tag.node_set.add(*nodes_matching)

开发者ID:maas,项目名称:maas,代码行数:25,

示例10: test_DictCharWidget_renders_with_empty_string_as_input_data

​点赞 6

# 需要导入模块: from lxml import etree [as 别名]

# 或者: from lxml.etree import XPath [as 别名]

def test_DictCharWidget_renders_with_empty_string_as_input_data(self):

names = [factory.make_string(), factory.make_string()]

initials = []

labels = [factory.make_string(), factory.make_string()]

widget = DictCharWidget(

[widgets.TextInput, widgets.TextInput, widgets.CheckboxInput],

names,

initials,

labels,

skip_check=True,

)

name = factory.make_string()

html_widget = fromstring(

"" + widget.render(name, "") + ""

)

widget_names = XPath("fieldset/input/@name")(html_widget)

widget_labels = XPath("fieldset/label/text()")(html_widget)

expected_names = [

"%s_%s" % (name, widget_name) for widget_name in names

]

self.assertEqual(

[expected_names, labels], [widget_names, widget_labels]

)

开发者ID:maas,项目名称:maas,代码行数:25,

示例11: filter_add

​点赞 5

# 需要导入模块: from lxml import etree [as 别名]

# 或者: from lxml.etree import XPath [as 别名]

def filter_add(self, xpath):

self.filters.append(ET.XPath(xpath))

开发者ID:openSUSE,项目名称:openSUSE-release-tools,代码行数:4,

示例12: group_by

​点赞 5

# 需要导入模块: from lxml import etree [as 别名]

# 或者: from lxml.etree import XPath [as 别名]

def group_by(self, xpath, required=False):

self.groups.append(ET.XPath(xpath))

if required:

self.filter_add(xpath)

开发者ID:openSUSE,项目名称:openSUSE-release-tools,代码行数:6,

示例13: makeXmlPageFromRaw

​点赞 5

# 需要导入模块: from lxml import etree [as 别名]

# 或者: from lxml.etree import XPath [as 别名]

def makeXmlPageFromRaw(xml):

""" Discard the metadata around a element in string"""

root = etree.XML(xml)

find = etree.XPath("//*[local-name() = 'page']")

# The tag will inherit the namespace, like:

#

# FIXME: pretty_print doesn't seem to work, only adds a newline

return etree.tostring(find(root)[0], pretty_print=True)

开发者ID:WikiTeam,项目名称:wikiteam,代码行数:10,

示例14: final_attribute_name

​点赞 5

# 需要导入模块: from lxml import etree [as 别名]

# 或者: from lxml.etree import XPath [as 别名]

def final_attribute_name(xpath):

"""

Find the final text element of an xpath which we will assume is the name

of an attribute.

TODO: find a better and less error-prone way to do this!

"""

if type(xpath) == XPath: ## in case compiled:

pathstring = xpath.path

else:

pathstring = xpath

fragments = re.split("[/:@\(\)]+", pathstring)

return fragments[-1]

开发者ID:CSTR-Edinburgh,项目名称:Ossian,代码行数:15,

示例15: _make_xpath_builder

​点赞 5

# 需要导入模块: from lxml import etree [as 别名]

# 或者: from lxml.etree import XPath [as 别名]

def _make_xpath_builder(self):

namespaces = {

'ds' : 'http://www.w3.org/2000/09/xmldsig#',

'md' : 'urn:oasis:names:tc:SAML:2.0:metadata',

'saml' : 'urn:oasis:names:tc:SAML:2.0:assertion',

'samlp': 'urn:oasis:names:tc:SAML:2.0:protocol'

}

def xpath_with_namespaces(xpath_str):

return etree.XPath(xpath_str, namespaces=namespaces)

return xpath_with_namespaces

开发者ID:bluedatainc,项目名称:jupyterhub-samlauthenticator,代码行数:14,

示例16: _get_username_from_saml_etree

​点赞 5

# 需要导入模块: from lxml import etree [as 别名]

# 或者: from lxml.etree import XPath [as 别名]

def _get_username_from_saml_etree(self, signed_xml):

xpath_with_namespaces = self._make_xpath_builder()

xpath_fun = xpath_with_namespaces(self.xpath_username_location)

xpath_result = xpath_fun(signed_xml)

if isinstance(xpath_result, etree._ElementUnicodeResult):

return xpath_result

if type(xpath_result) is list and len(xpath_result) > 0:

return xpath_result[0]

self.log.warning('Could not find name from name XPath')

return None

开发者ID:bluedatainc,项目名称:jupyterhub-samlauthenticator,代码行数:15,

示例17: _get_roles_from_saml_etree

​点赞 5

# 需要导入模块: from lxml import etree [as 别名]

# 或者: from lxml.etree import XPath [as 别名]

def _get_roles_from_saml_etree(self, signed_xml):

if self.xpath_role_location:

xpath_with_namespaces = self._make_xpath_builder()

xpath_fun = xpath_with_namespaces(self.xpath_role_location)

xpath_result = xpath_fun(signed_xml)

if xpath_result:

return xpath_result

self.log.warning('Could not find role from role XPath')

else:

self.log.warning('Role XPath not set')

return []

开发者ID:bluedatainc,项目名称:jupyterhub-samlauthenticator,代码行数:16,

示例18: lint_file

​点赞 5

# 需要导入模块: from lxml import etree [as 别名]

# 或者: from lxml.etree import XPath [as 别名]

def lint_file(filepath, file_contents, rules):

"""Run rules against file, yielding any failures."""

matching_rules = [

rule

for rule in rules

if rule_settings_match(rule, filepath)

]

if not matching_rules:

return

ignored_lines = get_ignored_lines(file_contents)

xml_ast = file_contents_to_xml_ast(file_contents) # todo - use caching module?

for rule in sorted(matching_rules, key=attrgetter('name')):

# TODO - hacky - need to find better way to do this (while keeping chain)

# TODO - possibly having both filepath and contents/input supplied?

if isinstance(rule.expr, XPath):

matching_lines = set(find_in_ast(

xml_ast,

rule.expr.path,

return_lines=True

))

elif isinstance(rule.expr, re._pattern_type):

matching_lines = {

file_contents[:match.start()].count('\n') + 1 # TODO - slow

for match in re.finditer(rule.expr, file_contents)

}

elif callable(rule.expr):

matching_lines = set(rule.expr(file_contents))

else:

continue # todo - maybe throw here?

if rule.settings.allow_ignore:

matching_lines -= ignored_lines

if not matching_lines:

yield LintingResult(rule, filepath, succeeded=True, lineno=None)

for line in matching_lines:

yield LintingResult(rule, filepath, succeeded=False, lineno=line)

开发者ID:hchasestevens,项目名称:bellybutton,代码行数:42,

示例19: xpath

​点赞 5

# 需要导入模块: from lxml import etree [as 别名]

# 或者: from lxml.etree import XPath [as 别名]

def xpath(loader, node):

"""Construct XPath expressions."""

value = loader.construct_scalar(node)

return XPath(value)

开发者ID:hchasestevens,项目名称:bellybutton,代码行数:6,

示例20: test_parse_rule_requires_settings

​点赞 5

# 需要导入模块: from lxml import etree [as 别名]

# 或者: from lxml.etree import XPath [as 别名]

def test_parse_rule_requires_settings():

"""Ensure parse_rule raises an exception if settings are not provided."""

with pytest.raises(InvalidNode):

parse_rule(

rule_name='',

rule_values=dict(

description='',

expr=XPath("//Num"),

example="a = 1",

instead="a = int('1')",

)

)

开发者ID:hchasestevens,项目名称:bellybutton,代码行数:14,

示例21: _xp_all_of

​点赞 5

# 需要导入模块: from lxml import etree [as 别名]

# 或者: from lxml.etree import XPath [as 别名]

def _xp_all_of(types):

xp = is_instance_xpath(types)

return XPath('''./descendant-or-self::*[

{predicate}

]'''.format(predicate=xp))

开发者ID:scrapinghub,项目名称:js2xml,代码行数:7,

示例22: is_instance

​点赞 5

# 需要导入模块: from lxml import etree [as 别名]

# 或者: from lxml.etree import XPath [as 别名]

def is_instance(tree, types=None):

if types is None:

types = (dict, list)

return XPath(is_instance_xpath(types))(tree)

开发者ID:scrapinghub,项目名称:js2xml,代码行数:6,

示例23: escape_text

​点赞 5

# 需要导入模块: from lxml import etree [as 别名]

# 或者: from lxml.etree import XPath [as 别名]

def escape_text(self, txt):

result = txt

for k,v in TiKZMaker.escapes.items():

result = result.replace(k,v)

return result

# get_all_text = etree.XPath('.//text()')

开发者ID:paaguti,项目名称:svg2tikz,代码行数:9,

示例24: css

​点赞 5

# 需要导入模块: from lxml import etree [as 别名]

# 或者: from lxml.etree import XPath [as 别名]

def css(self, css):

return etree.XPath(HTMLTranslator().css_to_xpath(css))(self.tree)

开发者ID:elliterate,项目名称:capybara.py,代码行数:4,

示例25: process_node_tags

​点赞 5

# 需要导入模块: from lxml import etree [as 别名]

# 或者: from lxml.etree import XPath [as 别名]

def process_node_tags(

rack_id,

nodes,

tag_name,

tag_definition,

tag_nsmap,

client,

batch_size=None,

):

"""Update the nodes for a new/changed tag definition.

:param rack_id: System ID for the rack controller.

:param nodes: List of nodes to process tags for.

:param client: A `MAASClient` used to fetch the node's details via

calls to the web API.

:param tag_name: Name of the tag to update nodes for

:param tag_definition: Tag definition

:param batch_size: Size of batch

"""

# We evaluate this early, so we can fail before sending a bunch of data to

# the server

xpath = etree.XPath(tag_definition, namespaces=tag_nsmap)

system_ids = [node["system_id"] for node in nodes]

process_all(

client,

rack_id,

tag_name,

tag_definition,

system_ids,

xpath,

batch_size=batch_size,

)

开发者ID:maas,项目名称:maas,代码行数:34,

示例26: is_compiled_xpath

​点赞 5

# 需要导入模块: from lxml import etree [as 别名]

# 或者: from lxml.etree import XPath [as 别名]

def is_compiled_xpath(xpath):

"""Is `xpath` a compiled expression?"""

return isinstance(xpath, etree.XPath)

开发者ID:maas,项目名称:maas,代码行数:5,

示例27: test_logs_to_specified_logger

​点赞 5

# 需要导入模块: from lxml import etree [as 别名]

# 或者: from lxml.etree import XPath [as 别名]

def test_logs_to_specified_logger(self):

xpath = etree.XPath("/foo:bar")

doc = etree.XML("")

root_logger = self.useFixture(FakeLogger())

callers_logger = Mock()

try_match_xpath(xpath, doc, callers_logger)

self.assertEqual("", root_logger.output)

self.assertThat(

callers_logger.warning,

MockCalledOnceWith(

"Invalid expression '%s': %s",

"/foo:bar",

"Undefined namespace prefix",

),

)

开发者ID:maas,项目名称:maas,代码行数:17,

示例28: test_merges_into_new_tree

​点赞 5

# 需要导入模块: from lxml import etree [as 别名]

# 或者: from lxml.etree import XPath [as 别名]

def test_merges_into_new_tree(self):

xml = self.do_merge_details(

{

"lshw": b"Hello",

"lldp": b"Hello",

}

)

# The presence of a getroot() method indicates that this is a

# tree object, not an element.

self.assertThat(xml, MatchesStructure(getroot=IsCallable()))

# The list tag can be obtained using an XPath expression

# starting from the root of the tree.

self.assertSequenceEqual(

["list"], [elem.tag for elem in xml.xpath("/list")]

)

开发者ID:maas,项目名称:maas,代码行数:17,

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值