Как использовать цикл, чтобы получить каждый элемент? - PullRequest
0 голосов
/ 25 сентября 2019
def get_first_profile_id(service):
    # Use the Analytics service object to get the first profile id.

    # Get a list of all Google Analytics accounts for this user
    accounts = service.management().accounts().list().execute()

    if accounts.get('items'):
        # Get the first Google Analytics account.
        account = accounts.get('items')[0].get('id')

        # Get a list of all the properties for the first account.
        properties = service.management().webproperties().list(
                accountId=account).execute()

        if properties.get('items'):
            # Get the first property id.
            property = properties.get('items')[0].get('id')

            # Get a list of all views (profiles) for the first property.
            profiles = service.management().profiles().list(
                    accountId=account,
                    webPropertyId=property).execute()

            if profiles.get('items'):
                # return the first view (profile) id.
                return profiles.get('items')[0].get('id')

    return None

Привет, ребята, я использую Google Analytics API для извлечения данных с помощью Python.Выше приведен пример кода, предоставленного Google.

Я хочу использовать циклы для извлечения каждого «представления (профиля) id» из каждого свойства каждой учетной записи.Однако приведенный выше код извлекает только первый идентификатор представления (профиля) первого свойства первого аккаунта.

Можете ли вы поделиться какими-либо предложениями?Спасибо за помощь!

Ответы [ 3 ]

2 голосов
/ 26 сентября 2019

Добавьте для цикла для xxx.get ('items') [0], чтобы просмотреть все элементы в account / properties / profile.Добавить профиль в список и вернуть результат после всех циклов.

def get_first_profile_id(service):
    # Use the Analytics service object to get the first profile id.

    # Get a list of all Google Analytics accounts for the authorized user.
    accounts = service.management().accounts().list().execute()

    if accounts.get('items'):
        result = []
        # Loop through Google Analytics account.
        for account_item in  accounts.get('items'):
            account = account_item.get('id')
            # Get a list of all the properties for the account.
            properties = service.management().webproperties().list(
                accountId=account).execute()

            if properties.get('items'):
                # Loop through property id.
                for property_item in  properties.get('items'):
                    property = property_item.get('id')

                    # Get a list of all views (profiles) for the property.
                    profiles = service.management().profiles().list(
                        accountId=account,
                        webPropertyId=property).execute()

                    if profiles.get('items'):
                        # append all view (profile) id in result list.
                        for profile_item in profiles.get('items'):
                            result.append(profile_item.get('id'))
        return result
    return None
1 голос
/ 26 сентября 2019

Я также хотел бы предоставить более удобочитаемое решение для новичка (без использования списка).

if profiles.get('items'):
    result = [] 
    for profile in profiles.get('items'):
        result.append(profile.get('id'))
    return result
1 голос
/ 26 сентября 2019

Заменить

if profiles.get('items'):
 # return the first view (profile) id.    
    return profiles.get('items')[0].get('id')

на

if profiles.get('items'):
 # return the first view (profile) id.    
    return [x.get('id') for x in profiles.get('items')]
...