本文整理汇总了Python中lxml.etree._Element方法的典型用法代码示例。如果您正苦于以下问题:Python etree._Element方法的具体用法?Python etree._Element怎么用?Python etree._Element使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类lxml.etree
的用法示例。
在下文中一共展示了etree._Element方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _parse_html
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import _Element [as 别名]
def _parse_html(cls, *, html_etree: etree._Element):
if html_etree is None:
raise ValueError("<Item: html_etree is expected>")
item_ins = cls()
fields_dict = getattr(item_ins, "__fields", {})
for field_name, field_value in fields_dict.items():
if not field_name.startswith("target_"):
clean_method = getattr(item_ins, f"clean_{field_name}", None)
value = field_value.extract(html_etree)
if clean_method is not None and callable(clean_method):
try:
aws_clean_func = clean_method(value)
if isawaitable(aws_clean_func):
value = await aws_clean_func
else:
raise InvalidFuncType(
f"<Item: clean_method must be a coroutine function>"
)
except IgnoreThisItem:
item_ins.ignore_item = True
setattr(item_ins, field_name, value)
item_ins.results[field_name] = value
return item_ins
示例2: extract
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import _Element [as 别名]
def extract(self, html_etree: etree._Element, is_source: bool = False):
elements = self._get_elements(html_etree=html_etree)
if is_source:
return elements if self.many else elements[0]
if elements:
results = [self._parse_element(element) for element in elements]
elif self.default is None:
raise NothingMatchedError(
f"Extract `{self.css_select or self.xpath_select}` error, "
"please check selector or set parameter named `default`"
)
else:
results = self.default if type(self.default) == list else [self.default]
return results if self.many else results[0]
示例3: invoice_to_xml
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import _Element [as 别名]
def invoice_to_xml(invoice: Invoice) -> etree._Element:
root_tag = "{%s}FatturaElettronica" % NAMESPACE_MAP["p"]
schema_location_key = "{%s}schemaLocation" % NAMESPACE_MAP["xsi"]
root = etree.Element(
root_tag,
attrib={schema_location_key: SCHEMA_LOCATION},
nsmap=NAMESPACE_MAP,
versione="FPR12",
)
header = _generate_header(invoice)
body = _generate_body(invoice)
tags = [*dict_to_xml(header), *dict_to_xml(body)]
for tag in tags:
root.append(tag)
return root
示例4: to_yaml
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import _Element [as 别名]
def to_yaml(obj):
""" Simplify yaml representation for pretty printing """
# Is there a better way to do this by adding a representation with yaml.Dumper?
# Ordered dict: http://pyyaml.org/ticket/29#comment:11
if obj is None or isstring(obj):
out = str(obj)
elif type(obj) in [int, float, bool]:
return obj
elif hasattr(obj, 'to_yaml'):
out = obj.to_yaml()
elif isinstance(obj, etree._Element):
out = etree.tostring(obj, pretty_print = True)
elif type(obj) == dict:
out = {}
for (var, value) in obj.items():
out[str(var)] = to_yaml(value)
elif hasattr(obj, 'tolist'):
# For numpy objects
out = to_yaml(obj.tolist())
elif isinstance(obj, collections.Iterable):
out = [to_yaml(item) for item in obj]
else:
out = str(obj)
return out
示例5: enter_classDefinition
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import _Element [as 别名]
def enter_classDefinition(self, tree: etree._Element):
# we don't know if variables are states
# yet, we need to wait until equations are parsed
self.scope_stack.append({
'time': self.sym.sym('time'),
'sample_times': [],
'var': OrderedDict(), # variables
'states': [], # list of which variables are states (based on der call)
'dvar': OrderedDict(), # derivative of variables
'eqs': [], # equations
'when_eqs': [], # when equations
'c': {}, # conditions
'pre_c': {}, # pre conditions
'p': [], # parameters and constants
'prop': {}, # properties for variables
'ng': [], # gaussian
'nu': [], # uniform
})
示例6: to_yaml
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import _Element [as 别名]
def to_yaml(obj):
""" Simplify yaml representation for pretty printing """
# Is there a better way to do this by adding a representation with yaml.Dumper?
# Ordered dict: http://pyyaml.org/ticket/29#comment:11
if obj is None or isstring(obj):
out = str(obj)
elif type(obj) in [int, float, bool]:
return obj
elif hasattr(obj, 'to_yaml'):
out = obj.to_yaml()
elif isinstance(obj, etree._Element):
out = etree.tostring(obj, pretty_print = True)
elif type(obj) == dict:
out = {}
for (var, value) in list(obj.items()):
out[str(var)] = to_yaml(value)
elif hasattr(obj, 'tolist'):
# For numpy objects
out = to_yaml(obj.tolist())
elif isinstance(obj, collections.Iterable):
out = [to_yaml(item) for item in obj]
else:
out = str(obj)
return out
示例7: __init__
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import _Element [as 别名]
def __init__(self, name=None, element=None, icon=None, notes=None,
kp=None, expires=None, expiry_time=None):
self._kp = kp
if element is None:
super(Group, self).__init__(
element=Element('Group'),
kp=kp,
expires=expires,
expiry_time=expiry_time,
icon=icon
)
self._element.append(E.Name(name))
if notes:
self._element.append(E.Notes(notes))
else:
assert type(element) in [_Element, Element, ObjectifiedElement], \
'The provided element is not an LXML Element, but {}'.format(
type(element)
)
assert element.tag == 'Group', 'The provided element is not a Group '\
'element, but a {}'.format(element.tag)
self._element = element
示例8: _extract_translatable_qweb_terms
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import _Element [as 别名]
def _extract_translatable_qweb_terms(element, callback):
""" Helper method to walk an etree document representing
a QWeb template, and call ``callback(term)`` for each
translatable term that is found in the document.
:param etree._Element element: root of etree document to extract terms from
:param Callable callback: a callable in the form ``f(term, source_line)``,
that will be called for each extracted term.
"""
# not using elementTree.iterparse because we need to skip sub-trees in case
# the ancestor element had a reason to be skipped
for el in element:
if isinstance(el, SKIPPED_ELEMENT_TYPES): continue
if (el.tag.lower() not in SKIPPED_ELEMENTS
and "t-js" not in el.attrib
and not ("t-jquery" in el.attrib and "t-operation" not in el.attrib)
and el.get("t-translation", '').strip() != "off"):
_push(callback, el.text, el.sourceline)
for att in ('title', 'alt', 'label', 'placeholder'):
if att in el.attrib:
_push(callback, el.attrib[att], el.sourceline)
_extract_translatable_qweb_terms(el, callback)
_push(callback, el.tail, el.sourceline)
示例9: extract_value
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import _Element [as 别名]
def extract_value(self, html, is_source=False):
"""
Use css_select or re_select to extract a field value
:return:
"""
value = ''
if self.css_select:
value = html.cssselect(self.css_select)
elif self.xpath_select:
value = html.xpath(self.xpath_select)
else:
raise ValueError('%s field: css_select or xpath_select is expected' % self.__class__.__name__)
if is_source:
return value
if isinstance(value, list) and len(value) == 1:
if isinstance(value[0], etree._Element):
text = ''
for node in value[0].itertext():
text += node.strip()
value = text
if isinstance(value[0], str) or isinstance(value[0], etree._ElementUnicodeResult):
value = ''.join(value)
if self.default is not None:
value = value if value else self.default
return value
示例10: to_xml
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import _Element [as 别名]
def to_xml(self, prefix_root=None, debug_context=None):
"""Generates an etree._Element corresponding to this MJCF element.
Args:
prefix_root: (optional) A `NameScope` object to be treated as root
for the purpose of calculating the prefix.
If `None` then no prefix is included.
debug_context: (optional) A `debugging.DebugContext` object to which
the debugging information associated with the generated XML is written.
This is intended for internal use within PyMJCF; users should never need
manually pass this argument.
Returns:
An etree._Element object.
"""
prefix_root = prefix_root or self.namescope
xml_element = etree.Element(self._spec.name)
self._attributes_to_xml(xml_element, prefix_root, debug_context)
self._children_to_xml(xml_element, prefix_root, debug_context)
return xml_element
示例11: write
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import _Element [as 别名]
def write(self, out):
target = E.Target(Name='Build')
if self.makedir:
target.append(E.MakeDir(Directories=self.makedir))
for line in self.commands:
if not isinstance(line, etree._Element): # pragma: no cover
raise TypeError('expected an lxml element')
target.append(line)
self._write(out, [
# Import the C++ properties to get $(OutDir). There might be a
# better way to handle this.
E.Import(Project=r'$(VCTargetsPath)\Microsoft.Cpp.default.props'),
E.Import(Project=r'$(VCTargetsPath)\Microsoft.Cpp.props'),
target
])
示例12: Query
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import _Element [as 别名]
def Query(self, uri):
"""Performs a query and returns a resulting feed or entry.
Args:
uri: A string representing the URI of the feed that is to be queried.
Returns:
On success, a tuple in the form:
(boolean succeeded=True, ElementTree._Element result)
On failure, a tuple in the form:
(boolean succeeded=False, {'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response})
"""
result = self.Get(uri)
return result
示例13: ExecuteWithPostData_FORM
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import _Element [as 别名]
def ExecuteWithPostData_FORM(session_id, uri, sub_url, timeout, post_data):
headers = CreateHeadersWithSessionCookieAndCustomHeader(session_id)
# TODO: another clue that refactor/redesign is required, xml testing if form code
if isinstance(post_data, etree._Element):
headers["Content-Type"] = "text/xml; charset=UTF-8"
post_data = as_string(post_data)
else:
headers["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8"
post_data = urllib.parse.urlencode(utf8_encoded(post_data)).encode(encoding="utf-8")
return ExecuteWebRequest(uri + sub_url, post_data, headers, timeout, lambda: 'POST')
示例14: ExecuteBasicWithElement
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import _Element [as 别名]
def ExecuteBasicWithElement(self, tag, extra_attributes, element_or_name, element_attributes=None, **kwargs):
self._RequireAnOpenSession()
request = BuildRequest(self._session_id, tag, extra_attributes)
if element_or_name is None:
pass
else:
if not isinstance(element_or_name, etree._Element):
element_or_name = create_element(element_or_name, element_attributes)
elif element_attributes is not None:
raise ValueError('element_attributes should be None')
request.append(element_or_name)
return self._Execute_APIv1d1(request, **kwargs)
示例15: RequestConsoleCommand
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import _Element [as 别名]
def RequestConsoleCommand(self, xml_or_command):
"""
Execute an arbitrary command on the Security Console.
This function will return a single ConsoleCommandResponse XML object (API 1.1).
"""
if isinstance(xml_or_command, etree._Element):
xml_command = xml_or_command
else:
xml_command = create_element("Command")
xml_command.text = xml_or_command
return self.ExecuteBasicWithElement("ConsoleCommandRequest", {}, xml_command)