Проблема с вложенными словарями, которые меняют определенные значения для разных объявлений - PullRequest
1 голос
/ 01 августа 2020

Я пытаюсь очистить ссылки на веб-сайте. Когда я перехожу по ссылке, это может быть либо реклама автомобилей, либо обычная реклама. Ключи, которые мне нужно очистить для обоих типов рекламы, одинаковы:

Для рекламы Motor - data = dict_keys ['header', 'description', 'currency', 'price', 'wish' , 'id', 'photos', 'section', 'age', 'spotlight', 'year', 'state', 'friendlyUrl', 'keyInfo', 'продавец', 'displayAttributes', 'countyTown', ' хлебные крошки ']

Для обычных объявлений - data = dict_keys ([' заголовок ',' описание ',' валюта ',' цена ',' разыскивается ',' идентификатор ',' фотографии ',' раздел ' , 'age', 'spotlight', 'year', 'state', 'friendlyUrl', 'keyInfo', 'seller', 'displayAttributes', 'countyTown', 'breadcrumbs'])

В Motor рекламирует данные, которые клавиша «хлебные крошки» дает мне

[{'name': 'motor',
  'displayName': 'Cars & Motor',
  'id': 1003,
  'title': 'Cars Motorbikes Trucks Caravans and More',
  'subdomain': 'www',
  'containsSubsections': True,
  'xtn2': 101},
 {'name': 'cars',
  'displayName': 'Cars',
  'id': 11,
  'title': 'Cars',
  'subdomain': 'cars',
  'containsSubsections': False,
  'xtn2': 142}]

, в то время как в обычных рекламных объявлениях «хлебные крошки» дает мне

[{'name': 'all',
  'displayName': 'All Sections',
  'id': 2066,
  'title': 'See Everything For Sale',
  'subdomain': 'www',
  'containsSubsections': True,
  'xtn2': 100},
 {'name': 'household',
  'displayName': 'House & DIY',
  'id': 1001,
  'title': 'House & DIY',
  'subdomain': 'www',
  'containsSubsections': True,
  'xtn2': 105},
 {'name': 'furniture',
  'displayName': 'Furniture & Interiors',
  'id': 3,
  'title': 'Furniture',
  'subdomain': 'www',
  'containsSubsections': True,
  'xtn2': 105},
 {'name': 'kitchenappliances',
  'displayName': 'Kitchen Appliances',
  'id': 1089,
  'title': 'Kitchen Appliances',
  'subdomain': 'www',
  'containsSubsections': False,
  'xtn2': 105}]

Я попытался получить данные Motor, вызвав ' xtn2 'ключ и значение с данными [' breadcrumbs '] [0] [' xtn2 '] == 101: и присвоение ему имени' motordata '

if data['breadcrumbs'][0]['xtn2'] == 101:
            motordata = data
            if motordata:
                motors = motordata['breadcrumbs'][0]['name']
                views = motordata['views']
                title = motordata['header']
                Adcounty = motordata['county']
                itemId = motordata['id']
                sellerId = motordata['seller']['id']
                sellerName = motordata['seller']['name']
                adCount = motordata['seller']['adCount']
                lifetimeAds = motordata['seller']['adCountStats']['lifetimeAdView']['value']
                currency = motordata['currency']
                price = motordata['price']
                adUrl = motordata['friendlyUrl']
                adAge = motordata['age']
                spotlight = motordata['spotlight']

и обычных данных с данными elif [' хлебные крошки '] [0] [' xtn2 '] == 100: с ame 'Allotherads'

elif data['breadcrumbs'][0]['xtn2'] == 100:
            Allotherads = alldata
            if Allotherads:
                views = Allotherads['views']
                title = Allotherads['header']
                itemId = Allotherads['id']
                Adcounty = Allotherads['county']
                # Adtown = alldata['countyTown']
                sellerId = Allotherads['seller']['id']
                sellerName = Allotherads['seller']['name']
                adCount = Allotherads['seller']['adCount']
                lifetimeAds = Allotherads['seller']['adCountStats']['lifetimeAdView']['value']
                currency = Allotherads['currency']
                price = Allotherads['price']
                adUrl = Allotherads['friendlyUrl']
                adAge = Allotherads['age']
                spotlight = Allotherads['spotlight']
                topSectionName = Allotherads['xitiAdData']['topSectionName']
                xtn2 = Allotherads['breadcrumbs'][2]['xtn2']
                subSection = Allotherads['breadcrumbs'][2]['displayName']

, но это не работает. Он просто очищает обычную рекламу, но не рекламу автомобилей. Где я ошибаюсь?

1 Ответ

0 голосов
/ 01 августа 2020

Разве вы не можете просто сделать (если возможны несколько моторных диктовок):

motordata = [x for x in data.get('breadcrumbs') if x.get('name') == "motor"]

или (если возможны только одни моторные данные:

motordata = next(iter([x for x in data.get('breadcrumbs') if x.get('name') == "motor"]))

next(iter()) здесь работает то же, что [0] в конце, но быстрее

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...