? Существует несколько более подробный синтаксис, необходимый для извлечения элементов из этого. Эм.
>>> from lxml import html, etree
>>> example = etree.fromstring("""
<group id="[email protected]" iconserver="1" iconfarm="1" lang="en-us" ispoolmoderated="0">
<name>GNEverybody</name>
<description>The group for GNE players</description>
<members>69</members>
<privacy>3</privacy>
<throttle count="10" mode="month" remaining="3" />
<restrictions photos_ok="1" videos_ok="1" images_ok="1" screens_ok="1" art_ok="1" safe_ok="1" moderate_ok="0" restricted_ok="0" has_geo="0" />
</group>
""")
# Attributes can be accessed in two ways:
>>> example.attrib # Returns a dictionary of key, value pairs
{'iconserver': '1', 'lang': 'en-us', 'ispoolmoderated': '0', 'id': '[email protected]', 'iconfarm': '1'}
>>> example.get('id') # Grabs a specific key in the attribs dict.
'[email protected]'
# Children elements are accessed using the getchildren() method:
>>> example.getchildren() # Returns a list of items.
[<Element name at 0x1007c7140>, <Element description at 0x1007c7190>, <Element members at 0x1007c71e0>, <Element privacy at 0x1007c7230>, <Element throttle at 0x1007c7280>, <Element restrictions at 0x1007c72d0>]
Один альтернативный способ извлечения детей использует XPath:
>>> example.xpath(u'//description') # returns a list of elements which matched the tag name.
[<Element description at 0x1004d82d0>]
Доступ пункты описания элемента так же, как родительский узел:
>>> desc = example.xpath(u'//description')
>>> desc[0].tag
'description'
>>> desc[0].attrib # This node has no attributes.
{}
Другие элементы могут иметь атрибуты, хотя :
>>> example.xpath(u'//restrictions')[0].attrib
{'photos_ok': '1', 'images_ok': '1', 'safe_ok': '1', 'has_geo': '0', 'screens_ok': '1', 'videos_ok': '1', 'moderate_ok': '0', 'restricted_ok': '0', 'art_ok': '1'}
Посмотрите на dir(example)
для получения полного списка методов, которые вы можете использовать на lxml.etree.Element
.
Это конечно похорошела! Спасибо, что указал мне на это. – VooDooNOFX