[英]AttributeError: 'NoneType' object has no attribute 'encode' while writing into file?
[英]AttributeError: 'NoneType' object has no attribute 'get' when writing into a file
我正在尝试从网站上抓取(对不同用户使用循环),然后将其保存在字典中并将其写入文件中。
问题是用户数以百计,并不是每个用户在 json 中都有相同的数据。 对于没有特定数据行的用户,它给了我这个错误。
for i in range(10):
u = User(list_of_users[i])
try:
data_list = [[u.name, u.full_name, u.date_of_birth
,u.current_age, p.job_info.get('UserId').get('JobId'), p.job_info_with_z.get('UserId').get('location')]]
except AttributeError:
data_list = [[u.name, u.full_name, u.date_of_birth
,u.current_age, p.job_info.get('UserId').get('JobId'), p.job_info_with_z.get('UserId').get('location')]]
with open('test_players_data.csv', 'a', newline='') as file:
writer = csv.writer(file, delimiter=',')
writer.writerows(data_list)
.name 调用一个方法来获取名称,就像 job_info 和 info_with_z 一样。
所以这适用于大多数用户,但对于没有“UserId”的用户,它会给我上述错误。 但是有些用户会有 UserId 但没有 UserIdWithZ。 我想跳过具有一些默认值的那些并继续抓取数据并将其写入文件中。 一旦失败,它就不会向前 go 前进。
必须有一种方法可以在不存在键的情况下提供默认值。 我已经修剪了数据。 所以每个用户都有超过 30 个不同的值,我试图在 4 个代码块中抓取它们。
示例数据
{
'UserId': {'jobId': '74', 'jobLocation': '72', 'jobType': '10'},
'UserIdWithZ: {'jobId': '74', 'jobLocation': '72', 'jobType': '10'}
}
我只希望在.csv 中的行/记录填充没有任何数据而不仅仅是失败的“”或“-”或“na”。
提前致谢
在您的情况下使用.get
指定默认值,
p.job_info.get('UserId', {}).get('JobId', '-')
如果您希望dict
链接下一个get
您需要将默认值指定为{}
。 如果job_info.get('UserId')
没有值,则None
将是默认值,它没有get
方法。
对所有.get
方法执行相同操作,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.