下面的代码使用 lastfm api 获取有关艺术家的信息。然后它将名称存储在 bands[Name] 中,并将艺术家的每个标签名称(例如:摇滚等)存储在 bands[Tags] 中。 它工作得很好并存储名称但它不适用于标签。出现:
Traceback (most recent call last):
File "C:/Users/Ozzy/PycharmProjects/getData/getData.py", line 19, in <module>
for tag in artist.find('tags').findall('tag'):
AttributeError: 'NoneType' object has no attribute 'findall'
演示错误的最小工作示例:
import xml.etree.ElementTree as ET
import requests
ID = 1
chosen = "U2"
artist = requests.get(
'http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=U2&api_key=b088cbedecd40b35dd89e90f55227ac2')
tree = ET.fromstring(artist.content)
for child in tree:
for artist in child:
print(artist)
for tag in artist.find('tags').findall('tag'):
print(tag.find('name').text)
响应格式如下:
<lfm status="ok">
<artist>
<name>U2</name>
<tags>
<tag>
<name>rock</name>
<url>https://www.last.fm/tag/rock</url>
</tag>
<tag>
<tag>
<name>alternative</name>
<url>https://www.last.fm/tag/alternative</url>
</tag>
</tags>
</artist>
</lfm>
完整的工作示例,代码获取来自特定国家/地区的顶级艺术家,然后收集有关艺术家的信息(没有获取和存储每个艺术家的标签,因为它出现上面的 NoneType 错误):
import xml.etree.ElementTree as ET
import requests
import json
ID = 1
api_key = "b088cbedecd40b35dd89e90f55227ac2"
bands = {}
# GET TOP ARTISTS
for i in range(2, 3):
artistslist = requests.get(
'http://ws.audioscrobbler.com/2.0/?method=geo.gettopartists&country=spain&page='+str(i) +'&api_key=' + api_key)
tree = ET.fromstring(artistslist.content)
for child in tree:
for artist in child.findall('artist'):
name = artist.find('name').text
url = artist.find('url').text
bands[ID] = {}
bands[ID]['ID'] = ID
bands[ID]['Name'] = name
bands[ID]['URL'] = url
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:
#for tag in artist.find('tags').findall('tag'):
#print(tag.find('name').text)
#bands[i][Tags] = tag.find('name').text
if (artist.get('size') == "large"):
if (artist.text is not None):
bands[i]['Image'] = artist.text
for bio in artist.findall('summary'):
if (bio.text is not None):
bands[i]['Description'] = bio.text
else:
bands[i]['Description'] = bio.text
print(bands[i]['Name'] + " INFO RETRIEVED")
with open('artists.json', 'w') as outfile:
json.dump(bands, outfile)
with open('artists.json') as data_file:
bands = json.load(data_file)
data_file.close()
你知道如何解决这个问题吗?
请您参考如下方法:
你的循环太深了一层。
<lfm status="ok"> --> tree
<artist> --> child in tree
<name>U2</name> --> for artist in child
<tags>..</tags>
<tags已经是 child 的一部分因此 artist.find('tags')将返回 None .
您可以将循环缩短为:
for band in bands.values():
url = 'http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist={}&api_key={}'.format(band['Name'], api_key)
artist = requests.get(url)
tree = ET.fromstring(artist.content)
if tree.find('artist') is None:
continue
for child in tree.find('artist').getchildren():
if child.get('size') == "large":
if (child.text is not None):
band['Image'] = child.text
for bio in child.findall('summary'):
if bio.text is not None:
band['Description'] = bio.text
else:
band['Description'] = ""
for tag in child.findall('tag'):
if band.get('Tags'):
band['Tags'].append(tag.find('name').text)
else:
band['Tags'] = [tag.find('name').text]
print(band['Name'] + " INFO RETRIEVED")
一些注意事项:
- 遍历
dict中的键更容易也更有效通过使用for k in my_dict或超过for val in my_dict.values()的值 - 您正在覆盖您的
Tags最后一个值,使用list并附加到它会确保您保存所有值 - 你的
if/else语句 (if (bio.text is not None):) 的行为与条件无关
