Iter through object并在组中追加

时间:2017-06-12 13:43:24

标签: django python-3.x django-views

我正试图弄清楚如何通过一个名为'item'的对象来实现。 'item'来自肥皂召唤的回应。所以我在下面提取了一个XML。然后使用'xml.etree.ElementTre'将其变为'item'。

xmlList = re.search('<getListResponse>(.+?)</getListResponse>', str(xmlList)).group(1)
item = ET.fromstring(xmlList)

以下是在响应中使用ElementTree之前的样子。

<OL>
    <LI>
        <name>Foo</name>                        
        <type>Spam</type>
        <group>Wood</group>
        <....>ETC</....>
    </LI>
    <LI>
        <name>BAR</name>                        
        <type>Spam</type>
        <group>Iron</group>
        <....>ETC</....>
    </LI>
</OL>

我想创建一个新列表,我可以从'LI'中选择每个'NAME',其中'GROUP'是'WOOD'。

我是新手,我想出的就是这个。

 for a in item.iter('name'):            
    woodList.append(a.text)

这将从所有'GROUP'中获取所有'NAME'。我尝试了一些IF。但无法找到正确的语法来检查它属于哪个'GROUP'。

非常感谢。

1 个答案:

答案 0 :(得分:1)

BeautifulSoup是一个很好的lib来处理这种查询

(pip install bs4)

from bs4 import BeautifulSoup

html_str =    "<OL><LI><name>Foo</name><type>Spam</type><group>Wood</group><....>ETC</....></LI><LI><name>BAR</name><type>Spam</type><group>Iron</group><....>ETC</....></LI></OL>"

soup = BeautifulSoup(html_str,'html.parser')

li_list = soup.find_all('li')

for li in li_list:    
    if li.find('group').get_text() == "Wood":
        print li.find('name').get_text() + ' has wood'    
    else:
        print li.find('name').get_text() + ' has not'