2013-11-19 3 views
0

В последние несколько дней я испытывал серьезные ушибы мозга, и хотя я уверен, что мог бы это сделать несколько месяцев назад, я в полной мере теряю, как извлечь элементы данных с этого выхода; :(Исходное извлечение XML-данных на основе Python

Возвращение из Grp = flickr.groups_getInfo(group_id = gid) дает

Grp =

<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> 

Для извлечения отдельных элементов данных, она должна быть:

group_id = Grp.id 
group_name = Grp.name 
safe_ok = Grp.restrictions.safe_ok 

И так далее

ответ

2

? Существует несколько более подробный синтаксис, необходимый для извлечения элементов из этого. Эм.

>>> 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.

2

Вариантом ответа @VooDooNOFX «s является использование lxml.objectify

>>> group = lxml.objectify.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>""") 
>>> group.get("id") 
'[email protected]' 
>>> group.name 
'GNEverybody' 
>>> group.restrictions.get("safe_ok") 
'1' 
>>> 
+0

Это конечно похорошела! Спасибо, что указал мне на это. – VooDooNOFX

Смежные вопросы