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

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

本文整理汇总了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;未经允许,请勿转载。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/231005.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • datagrip 2021 激活码 下载_通用破解码

    datagrip 2021 激活码 下载_通用破解码,https://javaforall.net/100143.html。详细ieda激活码不妨到全栈程序员必看教程网一起来了解一下吧!

    2022年3月16日
    312
  • 交换机在局域网内的日常工作有哪些_交换机组建内部局域网

    交换机在局域网内的日常工作有哪些_交换机组建内部局域网动态主机配置协议(DynamicHostConfigurationProtocol)每一台新接入的机器都通过DHCP协议,来这个共享的IP地址里申请,然后自动配置好就可以了。等人走了

    2022年8月3日
    8
  • 移动端开发需要注意事项

    移动端开发需要注意事项1.webkit内核中的一些私有的meta标签<metacontent=”width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0″name=”viewport”><metacontent=”yes”name=”apple-mobile-web-app-capable”>…

    2022年6月24日
    28
  • Python break 和 continue 语句

    Python break 和 continue 语句在Python中,break和continue语句用于改变普通循环的流程。通常情况下,循环遍历一段代码,直到判断条件为False。但有时,可能会希望不检测判断条件就可以终止当前迭代,甚至是整个循环。这种情况下,就需要使用break和continue语句。

    2022年6月10日
    29
  • TCPDF_TCP ACK

    TCPDF_TCP ACK新建一个文档对象$pdf=newTCPDF(PDF_PAGE_ORIENTATION,PDF_UNIT,PDF_PAGE_FORMAT,true,’UTF-8′,false);页面记得也设为utf-8 AddPage();新建一个pdf文档页面。Image($file,$x,$y,$w,$h,$type,$link,$align…

    2025年10月4日
    3
  • 明日之后js免费脚本_超强免杀工具

    明日之后js免费脚本_超强免杀工具 js脚本免杀工具免杀经验以及简单的分析文章作者:虫虫信息来源:邪恶八进制信息安全团队(www.eviloctal.com)本文所做的实验是以ah.js(冰狐的一个变种,附件中名为”病毒样本.txt”)为病毒样本进行的,其他js恶意代码没有测试。由于卡巴斯基对js的查杀力度比较大,再者我本机就安装了卡巴斯基,所以对其有少量额外的分析。菜鸟作品,难登大雅之堂,高手多多指教!^-^常规的思路就是将

    2022年8月20日
    31

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号