Retrieve attribute names and values with Python / lxml and XPath

后端 未结 2 852
青春惊慌失措
青春惊慌失措 2021-01-19 03:21

I am using XPath with Python lxml (Python 2). I run through two passes on the data, one to select the records of interest, and one to extract values from the data. Here is a

2条回答
  •  [愿得一人]
    2021-01-19 04:10

    You should try following:

    for node in nodes:
        print node.attrib
    

    This will return dict of all attributes of node as {'id': '1', 'weight': '80', 'height': '160'}

    If you want to get something like [('@id', '1'), ('@height', '160'), ('@weight', '80')]:

    list_of_attributes = []
    for node in nodes:
        attrs = []
        for att in node.attrib:
            attrs.append(("@" + att, node.attrib[att]))
        list_of_attributes.append(attrs)
    

    Output:

    [[('@id', '1'), ('@height', '160'), ('@weight', '80')], [('@id', '2'), ('@weight', '70')], [('@id', '3'), ('@height', '140')]]
    

提交回复
热议问题