【发布时间】:2021-10-16 09:29:37
【问题描述】:
[为清晰和更正而编辑] 为早早匆忙的帖子道歉。我 scraped 并获得了 json 格式的响应。 json代码如下:
{
"item":{
"itemid":7041360985,
:
:
:
"models":[
{
"itemid":7041360985,
"status":1,
"current_promotion_reserved_stock":0,
"name":"",
"promotionid":0,
"price":2524141,
"price_stocks":[
{
"model_id":65873300871,
"stockout_time":0,
"region":"MY",
"rebate":"None",
"price":4301287,
"promotion_type":0,
"allocated_stock":"None",
"shop_id":449183886,
"end_time":"None",
"stock_breakdown_by_location":[
],
"item_id":11825286664,
"promotion_id":0,
"purchase_limit":"None",
"start_time":"None",
"stock":3
}
],
"current_promotion_has_reserve_stock":false,
:
}
],
"min_purchase_limit":0,
:
}
如果可用,我正在尝试从每个型号中获取名称和价格详细信息。有时,根本没有模型,有时会有 4 个。
下面是我访问字典值的尝试,但我得到了这个:
type1 = 型号['名称'] TypeError: 字符串索引必须是整数
def parse_data(self, response):
resp = json.loads(response.body)
for model in resp.get('models'):
type1 = model['name']
# 'type1price': model['price'],
yield{
'product': resp.get('item').get('name'),
'upcoming_flash_sale': resp.get('item').get('name'),
'rating': resp.get('item').get('item_rating').get('rating_star'),
'review numbers': resp.get('item').get('cmt_count'),
'viewcount': resp.get('item').get('view_count'),
'likes': resp.get('item').get('liked_count'),
'type1': type1,
'location': resp.get('item').get('shop_location')
}
产品详细信息,例如喜欢、评论编号等,是从关键“型号”之外获得的。最后,我想将它们与从“模型”中获得的数据合并。
如果有多个项目模型字典,我如何循环遍历所有可用项目(如果没有,则不破坏代码)?
【问题讨论】:
-
似乎有一个顶级键
'item'您的代码没有处理。试试resp['item']['models']? -
对于给定的代码,你将如何获得
'type1': resp.get('models')[0]['name'], TypeError: 'NoneType' object is not subscriptable.?您从未在代码中使用过resp.get('models')[0]['name']表达式。你使用的是model[0]['name']。共享给定代码的输出回溯,以便我们查看哪一行是错误的 -
另外模型变量是字典而不是列表,所以模型[0]会给出关键错误
-
只需删除
[0]。model是一个字典,而不是一个列表。也就是说,yield看起来很奇怪。您可能希望显示您的确切预期输出,以便其他人可以帮助指导您。 -
这不会解决问题,因为我认为模型是 Nonetype。 OP 应该共享原始代码的回溯
标签: python json web-scraping