获取"标签的每个标签名称" xml响应的元素无效

时间:2017-11-27 18:06:16

标签: python xml

我从特定国家/地区获取顶级艺术家,然后我想存储每位艺术家的名称和标签。名称工作正常,但标签不起作用。标签是摇滚,爵士等类型。

获取标签的部分:

for child in tree:
    for artist in child:
        print(artist)
        for tag in artist.findall('tags'):
            print(tag)
            bands[i]['Tags'] = tag.text

但是它不能正常工作(标签)返回:

<Element 'name' at 0x00000211BBEB0F98>
<Element 'tags' at 0x00000211BBEBD638>

你知道如何在{}乐队中获取和痛苦的标签吗?例如,在上面的例子中,标签是摇滚,经典摇滚,爱尔兰,流行和替代。

响应的格式为:

<lfm status="ok">
<artist>
<name>U2</name>
<tags>
<tag>
<name>rock</name>
<url>https://www.last.fm/tag/rock</url>
</tag>
<tag>
<name>classic rock</name>
<url>https://www.last.fm/tag/classic+rock</url>
</tag>
<tag>
<name>irish</name>
<url>https://www.last.fm/tag/irish</url>
</tag>
<tag>
<name>pop</name>
<url>https://www.last.fm/tag/pop</url>
</tag>
<tag>
<name>alternative</name>
<url>https://www.last.fm/tag/alternative</url>
</tag>
</tags>

</artist>
</lfm>

最小可验证示例:

import xml.etree.ElementTree as ET
import requests

ID = 1

api_key = "b088cbedecd40b35dd89e90f55227ac2"  # generated for the example

bands = {}

# GET TOP ARTISTS

artistslist = requests.get(
    'http://ws.audioscrobbler.com/2.0/?method=geo.gettopartists&country=spain&page=1&limit=5&api_key=' + api_key)
tree = ET.fromstring(artistslist.content)
for child in tree:
    for artist in child.findall('artist'):
        name = artist.find('name').text
        bands[ID] = {}
        bands[ID]['ID'] = ID
        bands[ID]['Name'] = name

        ID += 1

# GET ARTIST INFO
for i, v in bands.items():

    chosen = bands[i]['Name'].replace(" ", "+")
    artist = requests.get(
        'http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=' + chosen + '&api_key=' + api_key)
    tree = ET.fromstring(artist.content)
    for child in tree:
        for artist in child:
            print(artist)
            for tag in artist.findall('tags'):
                print(tag['name'])
                bands[i]['Tags'] = tag.text
            if (artist.get('size') == "large"):
                if (artist.text is not None):
                    bands[i]['Image'] = artist.text

    print(bands[i]['Name'] + " RETRIEVED")

0 个答案:

没有答案
相关问题