人生苦短,我用python
爬取某DB电影数据的时候,
在获取内容的时候出现
'NoneType' object is not subscriptable
Python 资料+报错交流:点击此处跳转文末名片获取
获取数据的部分代码是:
writer_avatars = (writers_list[wi]['avatars']['small']) # 编剧照片writer_name_en = (writers_list[wi]['name_en'].replace("\'", "\\\'") # 编剧英文名writer_name = (writers_list[wi]['name'].replace("\'", "\\\'") # 编剧名字writer_alt = (writers_list[wi]['alt']) # 编剧在豆瓣中的个人主页urlwriter_id = writers_list[wi]['id'] # 编剧在豆瓣中个人idwriter_id_list.append(int(writer_id))
输出获取到的数据:
[
{'avatars': {'small': 'http://img1./view/celebrity/s_ratio_celebrity/public/p21289.jpg', 'large': 'http:///view/celebrity/s_ratio_celebrity/public/p21289.jpg', 'medium': 'http:///view/celebrity/s_ratio_celebrity/public/p21289.jpg'},
'name_en': 'Joe Ma',
'name': '马伟豪',
'alt': 'https:///celebrity/1290574/',
'id': '1290574'}, {'avatars': {'small': 'http:///view/celebrity/s_ratio_celebrity/public/p1455792638.81.jpg', 'large': 'http:///view/celebrity/s_ratio_celebrity/public/p1455792638.81.jpg', 'medium': 'http:///view/celebrity/s_ratio_celebrity/public/p1455792638.81.jpg'},
'name_en': 'Ivy Kong',
'name': '江玉仪',
'alt': '',
'id': '1275631'}, {'avatars': {'small': /p1496898017.43.jpg', 'large': 'http://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1496898017.43.jpg', 'medium': 'http://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1496898017.43.jpg'},
'name_en': 'Sunny Chan',
'name': '陈咏燊',
'alt': 'https:///celebrity/1375202/',
'id': '1375202'}, {'avatars': {'small': '/view/celebrity/s_ratio_celebrity/public/p3555.jpg', 'large': 'http://img9.doubanio.com/view/celebrity/s_ratio_celebrity/public/p3555.jpg', 'medium': 'http:///view/celebrity/s_ratio_celebrity/public/p3555.jpg'},
'name_en': 'Felix Chong',
'name': '庄文强',
'alt': 'https:///celebrity/1014716/',
'id': '1014716'}, {'avatars': None, 'name_en': '', 'name': '钟健强', 'alt': None, 'id': None},
{'avatars': None, 'name_en': '', 'name': '孙浩浩', 'alt': None, 'id': None}
]
可以看到之所以报错是因为 数据有为 None 的,
是因为 None 类型是不可编写的
解决如下:
①如果有为 None 的数据不需要保留的话那可以直接用try:pass except:pass 捕获异常,程序正常运行
②如果即使有为None的数据也需要保存的话可以加入判断:if ** is None: pass esle:pass
部分加入判断的代码如下:
if writers_list[wi]['avatars'] is None:writer_avatars = '暂无数据'else:if writers_list[wi]['avatars']['small'] is None:writer_avatars = '暂无数据'else:writer_avatars = (writers_list[wi]['avatars']['small']) # 编剧照片
这样既可既不报错又保留数据