Traceback (most recent call last): File "D:\Notepad++\b.py", line 57, in <module> playlists = get_playlists(soup) File "D:\Notepad++\b.py", line 25, in get_playlists playlist['create_time'] = li.find('span', {'class': 's-fc3'}).text AttributeError: 'NoneType' object has no attribute 'text'
时间: 2023-12-22 11:05:16 浏览: 74
浅谈Python traceback的优雅处理
这个错误是因为有些歌单没有“创建时间”这个标签,导致 `li.find('span', {'class': 's-fc3'})` 返回了 `None`。你可以在获取这个标签的时候进行判断,如果返回值为 `None`,则将 `playlist['create_time']` 赋值为 “无创建时间” 或者其他你认为合适的值。修改后的 `get_playlists` 函数如下:
```python
def get_playlists(soup):
playlists = []
for li in soup.find('ul', {'class': 'm-cvrlst f-cb'}).find_all('li'):
playlist = {}
playlist['id'] = li.find('a')['href'].split('=')[1]
playlist['name'] = li.find('a')['title']
playlist['play_count'] = li.find('span', {'class': 'nb'}).text
create_time = li.find('span', {'class': 's-fc3'})
playlist['create_time'] = '无创建时间' if create_time is None else create_time.text
playlist['create_user'] = li.find('a', {'class': 'nm nm-icn f-thide s-fc3'})['title']
playlist['type'] = li.find('span', {'class': 's-fc4'}).text
playlist['update_time'] = li.find('span', {'class': 's-fc4'}).text
playlist['collect_count'] = li.find('span', {'class': 'u-btni u-btni-fav '}).text
playlist['song_count'] = li.find('span', {'class': 's-fc3'}).text
playlist['description'] = li.find('div', {'class': 'u-cover u-cover-1'}).text
playlist['comment_count'] = li.find('span', {'class': 'u-btni u-btni-cmmt '}).text
playlist['share_count'] = li.find('span', {'class': 'u-btni u-btni-share '}).text
playlists.append(playlist)
return playlists
```
这样修改后,即使有些歌单没有“创建时间”这个标签也不会报错了,而是会将 `playlist['create_time']` 赋值为 “无创建时间”。
阅读全文