Фиды страниц динамических поисковых объявлений

По умолчанию динамические поисковые объявления (DSA) настроены для таргетинга на все веб-сайты или их части, не фокусируясь на URL-адресах конкретных страниц. Если вам нужно лучше контролировать URL-адреса, вы можете использовать фиды страниц DSA, чтобы точно указать, какие URL-адреса использовать с вашими динамическими поисковыми объявлениями. Когда вы предоставляете фид страниц своих продуктов и их целевых страниц, это помогает Google Рекламе определять, когда показывать вашу рекламу и куда направлять людей на вашем веб-сайте.

Существует два варианта создания каналов страниц.

  1. Фиды страниц на основе объектов . Это предпочтительный способ создания каналов страниц.
  2. Ленты страниц на основе каналов . Это устаревший маршрут Feed для создания фидов страниц.

Этот документ охватывает оба варианта.

Переход на DSA на основе активов

Процесс автоматической миграции

Google автоматически перенесет все существующие фиды страниц DSA после 27 апреля 2022 г. Мы настоятельно рекомендуем вручную перенести свои учетные записи до этого.

После переноса не будет связи между автоматически перенесенными активами и элементами фида, на которых они были основаны (нет общих идентификаторов). Кроме того, в то же время ваши системы должны будут обрабатывать как устаревшие, так и основанные на активах фиды страниц.

После запуска процесса автоматической миграции в ваших учетных записях доступ для записи к устаревшим каналам будет заблокирован.

График миграции

На следующей временной шкале показаны ключевые даты миграции фидов страниц DSA.

Доступные типы на основе активов Дата автоматического переноса
Google Реклама API версии 9.0 (ноябрь 2021 г.) 27 апреля 2022 г.

Гибридное обслуживание

Во время перехода на DSA на основе активов ваша учетная запись будет работать в гибридном режиме. Как устаревшие фиды, так и фиды на основе объектов будут по-прежнему показываться. Если в кампании есть как фид на основе объектов, так и устаревший фид, то при переносе будут показываться оба.

Часто задаваемые вопросы

Будут ли какие-либо пробелы в отчетной статистике во время миграции?

Пробелов в статистике можно избежать, если старые и новые фиды страниц создаются с перекрытием. Статистика каналов страниц определяется URL-адресом, а не идентификатором канала/актива. Чтобы убедиться, что пробелы отсутствуют, создайте активы (и свяжите AssetSet) перед удалением старых фидов. Автоматическая миграция Google не создаст пробелов.

Будут ли удалены старые фиды?

Да, со временем старые фиды будут удалены.

Можно ли обновить ярлыки без повторного создания актива?

Да, метки можно обновить с помощью обычной операции UPDATE актива. Это не влияет на статистику отчетов, которая всегда определяется по URL-адресу.

Рабочий процесс на основе активов для создания фидов страниц DSA

Создайте активы для каждой страницы вашего сайта

Сначала создайте Asset для каждого URL-адреса на вашем веб-сайте.

Ява

List<String> urls =
    ImmutableList.of(
        "http://www.example.com/discounts/rental-cars",
        "http://www.example.com/discounts/hotel-deals",
        "http://www.example.com/discounts/flight-deals");

// Creates one operation per URL.
List<AssetOperation> assetOperations = new ArrayList<>();
for (String url : urls) {
  PageFeedAsset pageFeedAsset =
      PageFeedAsset.newBuilder()
          // Sets the URL of the page to include.
          .setPageUrl(url)
          // Recommended: adds labels to the asset. These labels can be used later in ad group
          // targeting to restrict the set of pages that can serve.
          .addLabels(dsaPageUrlLabel)
          .build();
  Asset asset = Asset.newBuilder().setPageFeedAsset(pageFeedAsset).build();
  assetOperations.add(AssetOperation.newBuilder().setCreate(asset).build());
}

// Creates the service client.
try (AssetServiceClient assetServiceClient =
    googleAdsClient.getLatestVersion().createAssetServiceClient()) {
  // Adds the assets.
  MutateAssetsResponse response =
      assetServiceClient.mutateAssets(String.valueOf(customerId), assetOperations);
  // Prints some information about the result.
  List<String> resourceNames =
      response.getResultsList().stream()
          .map(MutateAssetResult::getResourceName)
          .collect(Collectors.toList());
  resourceNames.forEach(r -> System.out.printf("Created asset with resource name %s.%n", r));
  return resourceNames;
}
      

С#

/// <summary>
/// Creates Assets to be used in a DSA page feed.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="dsaPageUrlLabel">The DSA page URL label.</param>
/// <returns>The list of asset resource names.</returns>
private static List<string> CreateAssets(GoogleAdsClient client, long customerId,
    string dsaPageUrlLabel)
{
    AssetServiceClient assetService = client.GetService(Services.V11.AssetService);

    string[] urls = new[]
    {
        "http://www.example.com/discounts/rental-cars",
        "http://www.example.com/discounts/hotel-deals",
        "http://www.example.com/discounts/flight-deals"
    };

    // Creates one operation per URL.
    List<AssetOperation> assetOperations = new List<AssetOperation>();
    foreach (string url in urls)
    {
        PageFeedAsset pageFeedAsset = new PageFeedAsset()
        {
            // Sets the URL of the page to include.
            PageUrl = url,

            // Recommended: adds labels to the asset. These labels can be used later in
            // ad group targeting to restrict the set of pages that can serve.
            Labels = { dsaPageUrlLabel }
        };

        assetOperations.Add(
            new AssetOperation()
            {
                Create = new Asset()
                {
                    PageFeedAsset = pageFeedAsset
                }
            });
    }

    // Adds the assets.
    MutateAssetsResponse response =
        assetService.MutateAssets(customerId.ToString(), assetOperations);

    // Prints some information about the result.
    List<string> resourceNames = response.Results.Select(
        assetResult => assetResult.ResourceName).ToList();
    foreach (string resourceName in resourceNames)
    {
        Console.Write($"Created asset with resource name {resourceName}.");
    }
    return resourceNames;
}
      

PHP

$urls = [
    'http://www.example.com/discounts/rental-cars',
    'http://www.example.com/discounts/hotel-deals',
    'http://www.example.com/discounts/flight-deals'
];
$operations = [];
// Creates one asset per URL.
foreach ($urls as $url) {
    $pageFeedAsset = new PageFeedAsset([
        'page_url' => $url,
        // Recommended: adds labels to the asset. These labels can be used later in ad group
        // targeting to restrict the set of pages that can serve.
        'labels' => [$dsaPageUrlLabel]
    ]);

    // Wraps the page feed asset in an asset.
    $asset = new Asset(['page_feed_asset' => $pageFeedAsset]);

    // Creates an asset operation and adds it to the list of operations.
    $assetOperation = new AssetOperation();
    $assetOperation->setCreate($asset);
    $operations[] = $assetOperation;
}

// Issues a mutate request to add the assets and prints its information.
$assetServiceClient = $googleAdsClient->getAssetServiceClient();
$response = $assetServiceClient->mutateAssets(
    $customerId,
    $operations
);
$assetResourceNames = [];
printf("Added %d assets:%s", $response->getResults()->count(), PHP_EOL);
foreach ($response->getResults() as $addedAsset) {
    /** @var Asset $addedAsset */
    $assetResourceName = $addedAsset->getResourceName();
    printf(
        "Created an asset with resource name: '%s'.%s",
        $assetResourceName,
        PHP_EOL
    );
    $assetResourceNames[] = $assetResourceName;
}
return $assetResourceNames;
      

питон

def _create_assets(client, dsa_page_url_label, customer_id):
    """Creates Assets to be used in a DSA page feed.

    Args:
        client: an initialized GoogleAdsClient instance.
        dsa_page_url_label: a label for the DSA page URLs.
        customer_id: a client customer ID.

    Returns:
        a list of asset resource names.
    """
    urls = [
        "http://www.example.com/discounts/rental-cars",
        "http://www.example.com/discounts/hotel-deals",
        "http://www.example.com/discounts/flight-deals",
    ]

    operations = []
    for url in urls:
        operation = client.get_type("AssetOperation")
        page_feed_asset = operation.create.page_feed_asset
        page_feed_asset.page_url = url
        page_feed_asset.labels.append(dsa_page_url_label)
        operations.append(operation)

    asset_service = client.get_service("AssetService")
    response = asset_service.mutate_assets(
        customer_id=customer_id, operations=operations
    )

    resource_names = []
    for result in response.results:
        resource_name = result.resource_name
        print(f"Created asset with resource name '{resource_name}'")
        resource_names.append(resource_name)

    return resource_names
      

Рубин

def create_assets(client, dsa_page_url_label, customer_id)
  urls = [
    'http://www.example.com/discounts/rental-cars',
    'http://www.example.com/discounts/hotel-deals',
    'http://www.example.com/discounts/flight-deals',
  ]

  operations = urls.map do |url|
    client.operation.create_resource.asset do |asset|
      asset.page_feed_asset = client.resource.page_feed_asset do |pfa|
        # Sets the URL of the page to include.
        pfa.page_url = url
        # Recommended: adds labels to the asset. These labels can be used later
        # in ad group targeting to restrict the set of pages that can serve.
        pfa.labels << dsa_page_url_label
      end
    end
  end

  response = client.service.asset.mutate_assets(
    customer_id: customer_id,
    operations: operations,
  )

  resource_names = []
  response.results.each do |result|
    resource_name = result.resource_name
    puts "Created asset with resource name '#{resource_name}'"
    resource_names << resource_name
  end

  resource_names
end
      

Перл

my $urls = [
  "http://www.example.com/discounts/rental-cars",
  "http://www.example.com/discounts/hotel-deals",
  "http://www.example.com/discounts/flight-deals"
];

# Create one operation per URL.
my $asset_operations = [];
foreach my $url (@$urls) {
  my $page_feed_asset =
    Google::Ads::GoogleAds::V11::Common::PageFeedAsset->new({
      # Set the URL of the page to include.
      pageUrl => $url,
      # Recommended: add labels to the asset. These labels can be used later in
      # ad group targeting to restrict the set of pages that can serve.
      labels => [$dsa_page_url_label]});
  my $asset = Google::Ads::GoogleAds::V11::Resources::Asset->new({
    pageFeedAsset => $page_feed_asset
  });

  push @$asset_operations,
    Google::Ads::GoogleAds::V11::Services::AssetService::AssetOperation->new({
      create => $asset
    });
}

# Add the assets.
my $response = $api_client->AssetService()->mutate({
  customerId => $customer_id,
  operations => $asset_operations
});

# Print some information about the response.
my $resource_names = [];
foreach my $result (@{$response->{results}}) {
  push @$resource_names, $result->{resourceName};
  printf "Created asset with resource name '%s'.\n", $result->{resourceName};
}
return $resource_names;
      

Упакуйте активы веб-канала страницы в AssetSet

Затем создайте коллекцию активов, известную как AssetSet . Эта группа представляет все URL-адреса, которые следует учитывать для конкретной кампании. Asset может находиться в нескольких объектах AssetSet .

Сначала создайте новый AssetSet :

Ява

// Creates an AssetSet which will be used to link the dynamic page feed assets to a campaign.
AssetSet assetSet =
    AssetSet.newBuilder()
        .setName("My dynamic page feed " + CodeSampleHelper.getPrintableDateTime())
        .setType(AssetSetType.PAGE_FEED)
        .build();
// Creates an operation to add the AssetSet.
AssetSetOperation operation = AssetSetOperation.newBuilder().setCreate(assetSet).build();
try (AssetSetServiceClient serviceClient =
    googleAdsClient.getLatestVersion().createAssetSetServiceClient()) {
  // Sends the mutate request.
  MutateAssetSetsResponse response =
      serviceClient.mutateAssetSets(
          String.valueOf(params.customerId), ImmutableList.of(operation));
  // Prints some information about the response.
  String resourceName = response.getResults(0).getResourceName();
  System.out.printf("Created asset set with resource name %s.%n", resourceName);
  return resourceName;
}
      

С#

/// <summary>
/// Creates an AssetSet.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <returns>The resource name of the asset set.</returns>
private string CreateAssetSet(GoogleAdsClient client, long customerId)
{
    AssetSetServiceClient assetSetService = client.GetService(
        Services.V11.AssetSetService);

    // Creates an AssetSet which will be used to link the dynamic page feed assets
    // to a campaign.
    AssetSet assetSet = new AssetSet()
    {
        Name = "My dynamic page feed " + ExampleUtilities.GetRandomString(),
        Type = AssetSetType.PageFeed
    };

    // Creates an operation to add the AssetSet.
    AssetSetOperation operation = new AssetSetOperation()
    {
        Create = assetSet
    };

    // Sends the mutate request.
    MutateAssetSetsResponse response =
        assetSetService.MutateAssetSets(
            customerId.ToString(), new[] { operation });
    // Prints some information about the response.
    string resourceName = response.Results[0].ResourceName;
    Console.WriteLine($"Created asset set with resource name {resourceName}.");
    return resourceName;
}
      

PHP

// Creates an asset set which will be used to link the dynamic page feed assets to a
// campaign.
$assetSet = new AssetSet([
    'name' => 'My dynamic page feed ' . Helper::getPrintableDatetime(),
    'type' => AssetSetType::PAGE_FEED
]);

// Creates an asset set operation.
$assetSetOperation = new AssetSetOperation();
$assetSetOperation->setCreate($assetSet);

// Issues a mutate request to add the asset set and prints its information.
$assetSetServiceClient = $googleAdsClient->getAssetSetServiceClient();
$response = $assetSetServiceClient->mutateAssetSets(
    $customerId,
    [$assetSetOperation]
);
$assetSetResourceName = $response->getResults()[0]->getResourceName();
printf(
    "Created an asset set with resource name: '%s'.%s",
    $assetSetResourceName,
    PHP_EOL
);

return $assetSetResourceName;
      

питон

def _create_asset_set(client, customer_id):
    """Creates an AssetSet.

    The AssetSet will be used to link the dynamic page feed assets to a
    campaign.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID.

    Returns:
        an asset set resource name.
    """
    operation = client.get_type("AssetSetOperation")
    asset_set = operation.create
    asset_set.name = f"My dynamic page feed {datetime.now()}"
    asset_set.type_ = client.enums.AssetSetTypeEnum.PAGE_FEED

    asset_set_service = client.get_service("AssetSetService")
    response = asset_set_service.mutate_asset_sets(
        customer_id=customer_id, operations=[operation]
    )
    resource_name = response.results[0].resource_name
    print(f"Created asset set with resource name '{resource_name}'")

    return resource_name
      

Рубин

def create_asset_set(client, customer_id)
  # Creates an AssetSet which will be used to link the dynamic page feed assets to a campaign.
  # Creates an operation to add the AssetSet.
  operation = client.operation.create_resource.asset_set do |asset_set|
    asset_set.name = "My dynamic page feed #{Time.now}"
    asset_set.type = :PAGE_FEED
  end

  # Sends the mutate request.
  response = client.service.asset_set.mutate_asset_sets(
    customer_id: customer_id,
    operations: [operation],
  )
  # Prints some information about the response.
  resource_name = response.results.first.resource_name
  puts "Created asset set with resource name '#{resource_name}'"

  resource_name
end
      

Перл

# Create an AssetSet which will be used to link the dynamic page feed assets to
# a campaign.
my $asset_set = Google::Ads::GoogleAds::V11::Resources::AssetSet->new({
  name => "My dynamic page feed #" . uniqid(),
  type => PAGE_FEED
});

# Create an operation to add the AssetSet.
my $operation =
  Google::Ads::GoogleAds::V11::Services::AssetSetService::AssetSetOperation->
  new({
    create => $asset_set
  });

# Send the mutate request.
my $response = $api_client->AssetSetService()->mutate({
    customerId => $customer_id,
    operations => [$operation]});

# Print some information about the response.
my $resource_name = $response->{results}[0]{resourceName};
printf "Created asset set with resource name '%s'.\n", $resource_name;
return $resource_name;
      

Затем создайте связь между вашими активами сверху и AssetSet :

Ява

List<AssetSetAssetOperation> operations = new ArrayList<>();
for (String assetResourceName : assetResourceNames) {
  AssetSetAsset assetSetAsset =
      AssetSetAsset.newBuilder()
          .setAsset(assetResourceName)
          .setAssetSet(assetSetResourceName)
          .build();
  // Creates an operation to add the link.
  AssetSetAssetOperation operation =
      AssetSetAssetOperation.newBuilder().setCreate(assetSetAsset).build();
  operations.add(operation);
}
try (AssetSetAssetServiceClient client =
    googleAdsClient.getLatestVersion().createAssetSetAssetServiceClient()) {
  // Sends the mutate request.
  MutateAssetSetAssetsResponse response =
      client.mutateAssetSetAssets(String.valueOf(params.customerId), operations);
  // Prints some information about the response.
  String resourceName = response.getResults(0).getResourceName();
  System.out.printf("Created AssetSetAsset link with resource name %s.%n", resourceName);
}
      

С#

/// <summary>
/// Adds an Asset to an AssetSet by creating an AssetSetAsset link.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="assetResourceNames">The asset resource names.</param>
/// <param name="assetSetResourceName">Resource name of the asset set.</param>
private void AddAssetsToAssetSet(GoogleAdsClient client, long customerId,
    List<string> assetResourceNames, string assetSetResourceName)
{
    AssetSetAssetServiceClient assetSetAssetService = client.GetService(
        Services.V11.AssetSetAssetService);

    List<AssetSetAssetOperation> operations = new List<AssetSetAssetOperation>();
    foreach (string assetResourceName in assetResourceNames)
    {
        AssetSetAsset assetSetAsset = new AssetSetAsset()
        {
            Asset = assetResourceName,
            AssetSet = assetSetResourceName
        };

        // Creates an operation to add the link.
        AssetSetAssetOperation operation = new AssetSetAssetOperation()
        {
            Create = assetSetAsset
        };

        operations.Add(operation);
    }
    // Sends the mutate request.
    MutateAssetSetAssetsResponse response =
        assetSetAssetService.MutateAssetSetAssets(customerId.ToString(), operations);
    // Prints some information about the response.
    string resourceName = response.Results[0].ResourceName;
    Console.WriteLine($"Created AssetSetAsset link with resource name {resourceName}.");
}
      

PHP

$operations = [];
foreach ($assetResourceNames as $assetResourceName) {
    // Creates an asset set asset.
    $assetSetAsset = new AssetSetAsset([
        'asset' => $assetResourceName,
        'asset_set' => $assetSetResourceName
    ]);

    // Creates an asset set asset operation and adds it to the list of operations.
    $assetSetAssetOperation = new AssetSetAssetOperation();
    $assetSetAssetOperation->setCreate($assetSetAsset);
    $operations[] = $assetSetAssetOperation;
}

// Issues a mutate request to add the asset set assets and prints its information.
$assetSetAssetServiceClient = $googleAdsClient->getAssetSetAssetServiceClient();
$response = $assetSetAssetServiceClient->mutateAssetSetAssets(
    $customerId,
    $operations
);
printf("Added %d asset set assets:%s", $response->getResults()->count(), PHP_EOL);
foreach ($response->getResults() as $addedAssetSetAsset) {
    /** @var AssetSetAsset $addedAssetSetAsset */
    printf(
        "Created an asset set asset link with resource name: '%s'.%s",
        $addedAssetSetAsset->getResourceName(),
        PHP_EOL
    );
}
      

питон

def _add_assets_to_asset_set(
    client, asset_resource_names, asset_set_resource_name, customer_id
):
    """Adds an Asset to an AssetSet by creating an AssetSetAsset link.

    Args:
        client: an initialized GoogleAdsClient instance.
        asset_resource_names: a list of asset resource names.
        asset_set_resource_name: a resource name for an asset set.
        customer_id: a client customer ID.
    """
    operations = []
    for asset_resource_name in asset_resource_names:
        operation = client.get_type("AssetSetAssetOperation")
        asset_set_asset = operation.create
        asset_set_asset.asset = asset_resource_name
        asset_set_asset.asset_set = asset_set_resource_name
        operations.append(operation)

    asset_set_asset_service = client.get_service("AssetSetAssetService")
    response = asset_set_asset_service.mutate_asset_set_assets(
        customer_id=customer_id, operations=operations
    )
    resource_name = response.results[0].resource_name
    print(f"Created asset set asset with resource name '{resource_name}'")
      

Рубин

def add_assets_to_asset_set(client, asset_resource_names, asset_set_resource_name, customer_id)
  operations = asset_resource_names.map do |asset_resource_name|
    client.operation.create_resource.asset_set_asset do |asa|
      asa.asset = asset_resource_name
      asa.asset_set = asset_set_resource_name
    end
  end

  response = client.service.asset_set_asset.mutate_asset_set_assets(
    customer_id: customer_id,
    operations: operations,
  )
  resource_name = response.results.first.resource_name
  puts "Created asset set asset with resource name '#{resource_name}'"
end
      

Перл

my $operations = [];
foreach my $asset_resource_name (@$asset_resource_names) {
  my $asset_set_asset =
    Google::Ads::GoogleAds::V11::Resources::AssetSetAsset->new({
      asset    => $asset_resource_name,
      assetSet => $asset_set_resource_name
    });

  # Create an operation to add the link.
  my $operation =
    Google::Ads::GoogleAds::V11::Services::AssetSetAssetService::AssetSetAssetOperation
    ->new({
      create => $asset_set_asset
    });
  push @$operations, $operation;
}

# Send the mutate request.
my $response = $api_client->AssetSetAssetService()->mutate({
  customerId => $customer_id,
  operations => $operations
});

# Print some information about the response.
my $resource_name = $response->{results}[0]{resourceName};
printf "Created AssetSetAsset link with resource name '%s'.\n",
  $resource_name;
      

Свяжите AssetSet с кампанией

После того, как активы собраны в AssetSet , PageFeedAsset с кампанией.

Ява

// Creates a CampaignAssetSet representing the link between an AssetSet and a Campaign.
CampaignAssetSet campaignAssetSet =
    CampaignAssetSet.newBuilder()
        .setCampaign(ResourceNames.campaign(params.customerId, params.campaignId))
        .setAssetSet(assetSetResourceName)
        .build();
// Creates an operation to add the CampaignAssetSet.
CampaignAssetSetOperation operation =
    CampaignAssetSetOperation.newBuilder().setCreate(campaignAssetSet).build();
// Creates the service client.
try (CampaignAssetSetServiceClient client =
    googleAdsClient.getLatestVersion().createCampaignAssetSetServiceClient()) {
  // Issues the mutate request.
  MutateCampaignAssetSetsResponse response =
      client.mutateCampaignAssetSets(
          String.valueOf(params.customerId), ImmutableList.of(operation));
  String resourceName = response.getResults(0).getResourceName();
  System.out.printf("Created a CampaignAssetSet with resource name %s.%n", resourceName);
}
      

С#

/// <summary>
/// Links an AssetSet to a Campaign by creating a CampaignAssetSet.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="campaignId">ID of the campaign to which the asset is linked.</param>
/// <param name="assetSetResourceName">Resource name of the asset set.</param>
private void LinkAssetSetToCampaign(GoogleAdsClient client, long customerId,
    long campaignId, string assetSetResourceName)
{
    CampaignAssetSetServiceClient campaignAssetSetService = client.GetService(
        Services.V11.CampaignAssetSetService);

    // Creates a CampaignAssetSet representing the link between an AssetSet and a Campaign.
    CampaignAssetSet campaignAssetSet = new CampaignAssetSet()
    {
        Campaign = ResourceNames.Campaign(customerId, campaignId),
        AssetSet = assetSetResourceName,
    };

    // Creates an operation to add the CampaignAssetSet.
    CampaignAssetSetOperation operation = new CampaignAssetSetOperation()
    {
        Create = campaignAssetSet
    };
    // Issues the mutate request.
    MutateCampaignAssetSetsResponse response =
        campaignAssetSetService.MutateCampaignAssetSets(
            customerId.ToString(), new[] { operation });
    string resourceName = response.Results[0].ResourceName;
    Console.WriteLine($"Created a CampaignAssetSet with resource name {resourceName}.");
}
      

PHP

// Creates a campaign asset set representing the link between an asset set and a campaign.
$campaignAssetSet = new CampaignAssetSet([
    'asset_set' => $assetSetResourceName,
    'campaign' => ResourceNames::forCampaign($customerId, $campaignId)
]);

// Creates a campaign asset set operation.
$campaignAssetSetOperation = new CampaignAssetSetOperation();
$campaignAssetSetOperation->setCreate($campaignAssetSet);

// Issues a mutate request to add the campaign asset set and prints its information.
$campaignAssetSetServiceClient = $googleAdsClient->getCampaignAssetSetServiceClient();
$response = $campaignAssetSetServiceClient->mutateCampaignAssetSets(
    $customerId,
    [$campaignAssetSetOperation]
);
printf(
    "Created a campaign asset set with resource name: '%s'.%s",
    $response->getResults()[0]->getResourceName(),
    PHP_EOL
);
      

питон

def _link_asset_set_to_campaign(
    client, asset_set_resource_name, customer_id, campaign_id
):
    """Links an AssetSet to a Campaign by creating a CampaignAssetSet.

    Args:
        client: an initialized GoogleAdsClient instance.
        asset_set_resource_name: a resource name for an asset set.
        customer_id: a client customer ID.
        campaign_id: a campaign ID.
    """
    googleads_service = client.get_service("GoogleAdsService")
    operation = client.get_type("CampaignAssetSetOperation")
    campaign_asset_set = operation.create
    campaign_asset_set.campaign = googleads_service.campaign_path(
        customer_id, campaign_id
    )
    campaign_asset_set.asset_set = asset_set_resource_name

    campaign_asset_set_service = client.get_service("CampaignAssetSetService")
    response = campaign_asset_set_service.mutate_campaign_asset_sets(
        customer_id=customer_id, operations=[operation]
    )
    resource_name = response.results[0].resource_name
    print(f"Created a campaign asset set with resource name '{resource_name}'")
      

Рубин

def link_asset_set_to_campaign(client, asset_set_resource_name, customer_id, campaign_id)
  # Creates a CampaignAssetSet representing the link between an AssetSet and a Campaign.
  # Creates an operation to add the CampaignAssetSet.
  operation = client.operation.create_resource.campaign_asset_set do |cas|
    cas.campaign = client.path.campaign(customer_id, campaign_id)
    cas.asset_set = asset_set_resource_name
  end

  # Issues the mutate request.
  response = client.service.campaign_asset_set.mutate_campaign_asset_sets(
    customer_id: customer_id,
    operations: [operation],
  )
  resource_name = response.results.first.resource_name
  puts "Created a campaign asset set with resource name '#{resource_name}'"
end
      

Перл

# Create a CampaignAssetSet representing the link between an AssetSet and a Campaign.
my $campaign_asset_set =
  Google::Ads::GoogleAds::V11::Resources::CampaignAssetSet->new({
    campaign => Google::Ads::GoogleAds::V11::Utils::ResourceNames::campaign(
      $customer_id, $campaign_id
    ),
    assetSet => $asset_set_resource_name
  });

# Create an operation to add the CampaignAssetSet.
my $operation =
  Google::Ads::GoogleAds::V11::Services::CampaignAssetSetService::CampaignAssetSetOperation
  ->new({
    create => $campaign_asset_set
  });

# Issue the mutate request.
my $response = $api_client->CampaignAssetSetService()->mutate({
    customerId => $customer_id,
    operations => [$operation]});

# Print some information about the response.
my $resource_name = $response->{results}[0]{resourceName};
printf "Created a CampaignAssetSet with resource name '%s'.\n",
  $resource_name;
      

При желании вы можете использовать настраиваемые ярлыки для таргетинга и ставок на URL-адреса в ленте страниц. Это можно сделать, создав критерий на основе WebpageInfo , который фильтрует с использованием условия, operand которого задан как WebpageConditionOperand.CUSTOM_LABEL .

Ява

private static void addDsaTarget(
    GoogleAdsClient googleAdsClient, long customerId, long adGroupId, String dsaPageUrlLabel) {
  String adGroupResourceName = ResourceNames.adGroup(customerId, adGroupId);

  // Creates the webpage condition info that targets an advertiser's webpages based on the
  // custom label specified by the dsaPageUrlLabel (e.g. "discounts").
  WebpageConditionInfo webpageConditionInfo =
      WebpageConditionInfo.newBuilder()
          .setOperand(WebpageConditionOperand.CUSTOM_LABEL)
          .setArgument(dsaPageUrlLabel)
          .build();

  // Creates the webpage info, or criterion for targeting webpages of an advertiser's website.
  WebpageInfo webpageInfo =
      WebpageInfo.newBuilder()
          .setCriterionName("Test Criterion")
          .addAllConditions(ImmutableList.of(webpageConditionInfo))
          .build();

  // Creates the ad group criterion.
  AdGroupCriterion adGroupCriterion =
      AdGroupCriterion.newBuilder()
          .setAdGroup(adGroupResourceName)
          .setWebpage(webpageInfo)
          .setCpcBidMicros(1_500_000)
          .build();

  // Creates the operation.
  AdGroupCriterionOperation operation =
      AdGroupCriterionOperation.newBuilder().setCreate(adGroupCriterion).build();

  // Creates the service client.
  try (AdGroupCriterionServiceClient adGroupCriterionServiceClient =
      googleAdsClient.getLatestVersion().createAdGroupCriterionServiceClient()) {
    // Adds the ad group criterion.
    MutateAdGroupCriteriaResponse response =
        adGroupCriterionServiceClient.mutateAdGroupCriteria(
            Long.toString(customerId), ImmutableList.of(operation));

    // Displays the results.
    System.out.printf(
        "Created ad group criterion with resource name '%s'.%n",
        response.getResults(0).getResourceName());
  }
}
      

С#

private void AddDsaTarget(GoogleAdsClient client, long customerId, long adGroupId,
    string dsaPageUrlLabel)
{
    // Get the AdGroupCriterionService.
    AdGroupCriterionServiceClient adGroupCriterionService = client.GetService(
        Services.V11.AdGroupCriterionService);

    // Create the webpage condition info.
    WebpageConditionInfo webpageConditionInfo = new WebpageConditionInfo()
    {
        Operand = WebpageConditionOperand.CustomLabel,
        Argument = dsaPageUrlLabel,
    };

    // Creates the webpage info.
    WebpageInfo webpageInfo = new WebpageInfo()
    {
        CriterionName = "Test Criterion",
        Conditions = { webpageConditionInfo }
    };

    // Creates the ad group criterion.
    AdGroupCriterion adGroupCriterion = new AdGroupCriterion()
    {
        AdGroup = ResourceNames.AdGroup(customerId, adGroupId),
        Webpage = webpageInfo,
        CpcBidMicros = 1_500_000
    };

    // Create the operation.
    AdGroupCriterionOperation operation = new AdGroupCriterionOperation()
    {
        Create = adGroupCriterion
    };

    // Add the ad group criterion.
    MutateAdGroupCriteriaResponse mutateAdGroupCriteriaResponse =
        adGroupCriterionService.MutateAdGroupCriteria(customerId.ToString(),
            new[] { operation });

    // Display the results.
    foreach (MutateAdGroupCriterionResult result in mutateAdGroupCriteriaResponse.Results)
    {
        Console.WriteLine($"Created ad group criterion with resource name " +
            $"'{result.ResourceName}'.");
    }
}
      

PHP

public static function addDsaTarget(
    GoogleAdsClient $googleAdsClient,
    int $customerId,
    int $adGroupId,
    string $dsaPageUrlLabel
) {
    // Creates the webpage condition info.
    $webPageConditionInfo = new WebpageConditionInfo([
        'operand' => WebpageConditionOperand::CUSTOM_LABEL,
        'argument' => $dsaPageUrlLabel
    ]);

    // Creates the webpage info.
    $webPageInfo = new WebpageInfo([
        'criterion_name' => 'Test Criterion',
        'conditions' => [$webPageConditionInfo]
    ]);

    // Creates the ad group criterion.
    $adGroupCriterion = new AdGroupCriterion([
        'ad_group' => ResourceNames::forAdGroup($customerId, $adGroupId),
        'webpage' => $webPageInfo,
        'cpc_bid_micros' => 1500000
    ]);

    // Creates the operation.
    $adGroupCriterionOperation = new AdGroupCriterionOperation();
    $adGroupCriterionOperation->setCreate($adGroupCriterion);

    $adGroupCriterionServiceClient = $googleAdsClient->getAdGroupCriterionServiceClient();
    $response = $adGroupCriterionServiceClient->mutateAdGroupCriteria(
        $customerId,
        [$adGroupCriterionOperation]
    );

    $adGroupCriterionResourceName = $response->getResults()[0]->getResourceName();
    printf(
        "Created ad group criterion with resource name '%s'.%s",
        $adGroupCriterionResourceName,
        PHP_EOL
    );
}
      

питон

def _add_dsa_targeting(client, customer_id, ad_group_resource_name, label):
    """Adds Dynamic Search Ad targeting criteria to the given ad group.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID str.
        ad_group_resource_name: a resource_name str for an Ad Group.
        label: a Dynamic Search Ad URL label str.
    """
    # Retrieve a new ad group criterion operation object.
    ad_group_criterion_operation = client.get_type("AdGroupCriterionOperation")
    # Create a new ad group criterion.
    ad_group_criterion = ad_group_criterion_operation.create
    ad_group_criterion.ad_group = ad_group_resource_name
    # Set the custom bid for this criterion.
    ad_group_criterion.cpc_bid_micros = 1500000
    ad_group_criterion.webpage.criterion_name = "Test criterion"
    # Add a condition for label=specified_label_name
    webpage_criterion_info = client.get_type(
        "WebpageConditionInfo"
    )  # ad_group_criterion.webpage.conditions.add()
    webpage_criterion_info.argument = label
    webpage_criterion_info.operand = (
        client.enums.WebpageConditionOperandEnum.CUSTOM_LABEL
    )
    ad_group_criterion.webpage.conditions.append(webpage_criterion_info)

    # Retrieve the ad group criterion service.
    ad_group_criterion_service = client.get_service("AdGroupCriterionService")
    response = ad_group_criterion_service.mutate_ad_group_criteria(
        customer_id=customer_id, operations=[ad_group_criterion_operation]
    )
    resource_name = response.results[0].resource_name

    # Display the results.
    print(f"Created ad group criterion with resource_name: '{resource_name}'")
      

Рубин

def add_dsa_targeting(client, customer_id, ad_group_resource_name, label)
  webpage_condition_info = client.resource.webpage_condition_info do |wci|
    wci.operand = :CUSTOM_LABEL
    wci.argument = label
  end

  webpage_criterion = client.resource.webpage_info do |wi|
    wi.criterion_name = "Test criterion"
    wi.conditions << webpage_condition_info
  end

  ad_group_criterion = client.resource.ad_group_criterion do |agc|
    agc.ad_group = ad_group_resource_name
    agc.webpage = webpage_criterion
    agc.cpc_bid_micros = 1_500_000
  end

  op = client.operation.create_resource.ad_group_criterion(ad_group_criterion)

  response = client.service.ad_group_criterion.mutate_ad_group_criteria(
    customer_id: customer_id,
    operations: [op],
  )

  puts "Created ad group criterion with id: #{response.results.first.resource_name}"
end
      

Перл

sub add_dsa_target {
  my ($api_client, $customer_id, $ad_group_id, $dsa_page_url_label) = @_;

  my $ad_group_resource_name =
    Google::Ads::GoogleAds::V11::Utils::ResourceNames::ad_group($customer_id,
    $ad_group_id);

  # Create the webpage condition info.
  my $web_page_condition_info =
    Google::Ads::GoogleAds::V11::Common::WebpageConditionInfo->new({
      operand  => CUSTOM_LABEL,
      argument => $dsa_page_url_label
    });

  # Create the webpage info.
  my $web_page_info = Google::Ads::GoogleAds::V11::Common::WebpageInfo->new({
      criterionName => "Test Criterion",
      conditions    => [$web_page_condition_info]});

  # Create the ad group criterion.
  my $ad_group_criterion =
    Google::Ads::GoogleAds::V11::Resources::AdGroupCriterion->new({
      adGroup      => $ad_group_resource_name,
      webpage      => $web_page_info,
      cpcBidMicros => 1500000
    });

  # Create the operation.
  my $ad_group_criterion_operation =
    Google::Ads::GoogleAds::V11::Services::AdGroupCriterionService::AdGroupCriterionOperation
    ->new({
      create => $ad_group_criterion
    });

  my $ad_group_criteria_response =
    $api_client->AdGroupCriterionService()->mutate({
      customerId => $customer_id,
      operations => [$ad_group_criterion_operation]});

  printf "Created ad group criterion with resource name: '%s'.\n",
    $ad_group_criteria_response->{results}[0]{resourceName};
}
      

Устаревший: рабочий процесс на основе сервисов фидов для создания фидов страниц DSA.

Чтобы настроить Feed страниц DSA с сервисами фидов:

  1. Создайте канал и заполните его URL-адресами страниц.
  2. Настройте кампанию для использования фида страниц DSA.
  3. Необязательно, но рекомендуется . Добавьте пользовательские ярлыки к URL-адресам в фиде страниц, чтобы классифицировать и упорядочить цели для ваших динамических поисковых объявлений.

Создание ленты страниц (устаревшая версия)

Первым шагом в использовании фидов страниц DSA является создание фида с полем criterion_type FeedMapping , установленным как DSA_PAGE_FEED . Процедура аналогична описанной в нашем руководстве по сервисам фидов , за исключением следующих отличий.

  1. Каналы страниц DSA используют поле criterion_type вместо поля placeholder_type для установки цели FeedMapping .
  2. Вам нужно только создать фид, заполнить элементы и сопоставить фид с полями критерия фида страницы DSA.
DsaPageFeedCriterionField Описание Необходимый? Тип данных
PAGE_URL URL-адрес веб-страницы, на которую вы хотите настроить таргетинг. Да URL или URL_LIST
ЭТИКЕТКА Ярлыки, которые помогут вам настроить таргетинг объявлений в ленте страниц.

Он не должен содержать следующие строковые шаблоны: *, >>, ==, &+.

Нет STRING_LIST

Настройка кампании для фидов страниц (устаревшая версия)

Вы можете настроить кампанию DSA для использования фидов страниц, установив поле feeds в DynamicSearchAdsSetting .

Начните с получения параметра DynamicSearchAdSetting для вашей кампании с динамическими поисковыми объявлениями.

Ява

private static DynamicSearchAdsSetting getDsaSetting(
    GoogleAdsClient googleAdsClient, long customerId, long campaignId) {
  // Creates the query.
  String query =
      String.format(
          "SELECT campaign.id, "
              + " campaign.name, "
              + " campaign.dynamic_search_ads_setting.use_supplied_urls_only "
              + "FROM campaign "
              + "WHERE campaign.id = '%s'",
          campaignId);

  // Creates the request.
  SearchGoogleAdsRequest request =
      SearchGoogleAdsRequest.newBuilder()
          .setCustomerId(Long.toString(customerId))
          .setPageSize(PAGE_SIZE)
          .setQuery(query)
          .build();

  // Creates the service client.
  try (GoogleAdsServiceClient googleAdsServiceClient =
      googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
    // Issues the search request.
    SearchPagedResponse response = googleAdsServiceClient.search(request);

    // Throws an exception if the campaign is not a DSA campaign.
    // The server will return an error when trying to update the campaign with the DSA feed in
    // the following step if the campaign is not a DSA campaign. However, this
    // exception is easier to interpret.
    if (!response
        .getPage()
        .getResponse()
        .getResults(0)
        .getCampaign()
        .hasDynamicSearchAdsSetting()) {
      throw new IllegalArgumentException("Campaign with ID '%s' is not a DSA campaign.");
    }

    // Retrieves and returns the DSA setting.
    return response
        .getPage()
        .getResponse()
        .getResults(0)
        .getCampaign()
        .getDynamicSearchAdsSetting();
  }
}
      

С#

private DynamicSearchAdsSetting GetDsaSetting(GoogleAdsClient client, long customerId,
    long campaignId)
{
    // Get the GoogleAdsService.
    GoogleAdsServiceClient googleAdsService = client.GetService(
        Services.V11.GoogleAdsService);

    // Creates the query.
    // You must request all DSA fields in order to update the DSA settings in the
    // following step.
    string query =
        $@"SELECT
              campaign.id,
              campaign.name,
              campaign.dynamic_search_ads_setting.use_supplied_urls_only
          FROM
              campaign
          WHERE
              campaign.id = {campaignId}";

    GoogleAdsRow result = googleAdsService.Search(
        customerId.ToString(), query).FirstOrDefault();

    if (result == null)
    {
        throw new Exception("No campaign found with ID: " + campaignId);
    }

    // Gets the DSA settings.
    DynamicSearchAdsSetting dynamicSearchAdsSetting =
        result.Campaign.DynamicSearchAdsSetting;

    // Throws an exception if the campaign is not a DSA campaign.
    if (dynamicSearchAdsSetting == null)
    {
        throw new Exception($"Campaign with ID {campaignId} is not a DSA campaign.");
    }

    return dynamicSearchAdsSetting;
}
      

PHP

private static function getDsaSetting(
    GoogleAdsClient $googleAdsClient,
    int $customerId,
    int $campaignId
) {
    // Creates the query.
    $query = "SELECT campaign.id, campaign.name, " .
    "campaign.dynamic_search_ads_setting.use_supplied_urls_only " .
    "FROM campaign where campaign.id = $campaignId";

    $googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();
    $response = $googleAdsServiceClient->search(
        $customerId,
        $query,
        ['pageSize' => self::PAGE_SIZE, 'returnTotalResultsCount' => true]
    );

    // Throws an exception if a campaign with the provided ID does not exist.
    if ($response->getPage()->getResponseObject()->getTotalResultsCount() === 0) {
        throw new \InvalidArgumentException("No campaign found with ID $campaignId");
    }

    /** @var Campaign $campaign */
    $campaign = $response->getPage()->getResponseObject()->getResults()[0]->getCampaign();
    $dynamicSearchAdsSetting = $campaign->getDynamicSearchAdsSetting();

    // Throws an exception if the campaign is not a DSA campaign.
    if (is_null($dynamicSearchAdsSetting)) {
        throw new \InvalidArgumentException(
            "Campaign with ID $campaignId is not a DSA campaign."
        );
    }

    return $dynamicSearchAdsSetting;
}
      

питон

def _update_campaign_dsa_setting(
    client, customer_id, campaign_id, feed_details
):
    """Updates the given campaign with the given feed details.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID str.
        campaign_id: a campaign ID str;
        feed_details: a FeedDetails instance with feed attribute information.
    """
    query = f"""
        SELECT
            campaign.id,
            campaign.name,
            campaign.dynamic_search_ads_setting.use_supplied_urls_only
        FROM
            campaign
        WHERE
            campaign.id = {campaign_id}
        LIMIT 1
    """

    ga_service = client.get_service("GoogleAdsService")
    search_request = client.get_type("SearchGoogleAdsRequest")
    search_request.customer_id = customer_id
    search_request.query = query

    results = ga_service.search(request=search_request)

    campaign = None
    for row in results:
        campaign = row.campaign
      

Рубин

def update_campaign_dsa_setting(client, customer_id, campaign_id, feed_details)
  query = <<~EOD
    SELECT
      campaign.id,
      campaign.name,
      campaign.dynamic_search_ads_setting.feeds
    FROM
      campaign
    WHERE
      campaign.id = #{campaign_id}
    LIMIT 1000
  EOD
  response = client.service.google_ads.search(
    customer_id: customer_id,
    query: query,
  )

  result = response.first
      

Перл

sub get_dsa_setting {
  my ($api_client, $customer_id, $campaign_id) = @_;

  # Create the query.
  # You must request all DSA fields in order to update the DSA settings in the
  # following step.
  my $search_query =
    "SELECT campaign.id, campaign.name, " .
    "campaign.dynamic_search_ads_setting.use_supplied_urls_only " .
    "FROM campaign where campaign.id = $campaign_id";

  my $search_response = $api_client->GoogleAdsService()->search({
    customerId => $customer_id,
    query      => $search_query,
    pageSize   => PAGE_SIZE
  });

  # Die if a campaign with the provided ID does not exist.
  die "No campaign found with ID $campaign_id.\n"
    if scalar @{$search_response->{results}} == 0;

  my $dynamic_search_ads_setting =
    $search_response->{results}[0]{campaign}{dynamicSearchAdsSetting};

  # Die if the campaign is not a DSA campaign.
  die "Campaign with ID $campaign_id is not a DSA campaign.\n"
    if not $dynamic_search_ads_setting;

  return $dynamic_search_ads_setting;
}
      

Затем установите фиды страниц, указав имена их ресурсов в поле feeds DynamicSearchAdsSetting вашей кампании. При желании вы можете использовать поле use_supplied_urls_only , чтобы указать, следует ли использовать только указанные URL-адреса для ваших динамических поисковых объявлений.

Ява

private static void updateCampaignDsaSetting(
    GoogleAdsClient googleAdsClient, long customerId, String feedResourceName, long campaignId) {
  // Retrieves the existing dynamic search ads settings for the campaign.
  DynamicSearchAdsSetting dsaSetting = getDsaSetting(googleAdsClient, customerId, campaignId);
  dsaSetting.toBuilder().addAllFeeds(ImmutableList.of(feedResourceName)).build();

  // Creates the campaign object to update.
  Campaign campaign =
      Campaign.newBuilder()
          .setResourceName(ResourceNames.campaign(customerId, campaignId))
          .setDynamicSearchAdsSetting(dsaSetting)
          .build();

  // Creates the update operation and sets the update mask.
  CampaignOperation operation =
      CampaignOperation.newBuilder()
          .setUpdate(campaign)
          .setUpdateMask(FieldMasks.allSetFieldsOf(campaign))
          .build();

  // Creates the service client.
  try (CampaignServiceClient campaignServiceClient =
      googleAdsClient.getLatestVersion().createCampaignServiceClient()) {
    // Updates the campaign.
    MutateCampaignsResponse response =
        campaignServiceClient.mutateCampaigns(
            Long.toString(customerId), ImmutableList.of(operation));

    // Displays the results.
    System.out.printf(
        "Updated campaign with resource name '%s'.%n", response.getResults(0).getResourceName());
  }
}
      

С#

private void UpdateCampaignDsaSetting(GoogleAdsClient client, long customerId,
    string feedResourceName, long campaignId)
{
    // Get the CampaignService.
    CampaignServiceClient campaignService = client.GetService(
        Services.V11.CampaignService);

    DynamicSearchAdsSetting dsaSetting = GetDsaSetting(client, customerId, campaignId);
    dsaSetting.Feeds.Add(feedResourceName);

    // Create the campaign.
    Campaign campaign = new Campaign()
    {
        ResourceName = ResourceNames.Campaign(customerId, campaignId),
        DynamicSearchAdsSetting = dsaSetting
    };

    // Create the operation.
    CampaignOperation operation = new CampaignOperation()
    {
        Update = campaign,
        UpdateMask = FieldMasks.AllSetFieldsOf(campaign)
    };

    // Update the campaign.
    MutateCampaignsResponse response =
        campaignService.MutateCampaigns(customerId.ToString(), new[] { operation });
    // Display the results.
    foreach (MutateCampaignResult mutateCampaignResult in response.Results)
    {
        Console.WriteLine($"Updated campaign with resourceName: " +
            $"'{mutateCampaignResult.ResourceName}'.");
    }
}
      

PHP

private static function updateCampaignDsaSetting(
    GoogleAdsClient $googleAdsClient,
    int $customerId,
    array $feedDetails,
    int $campaignId
) {
    // Retrieves the existing dynamic search ads settings for the campaign.
    $dsaSetting = self::getDsaSetting(
        $googleAdsClient,
        $customerId,
        $campaignId
    );

    $dsaSetting->setFeeds([$feedDetails['resource_name']]);

    // Creates the campaign object to be updated.
    $campaign = new Campaign([
        'resource_name' => ResourceNames::forCampaign($customerId, $campaignId),
        'dynamic_search_ads_setting' => $dsaSetting
    ]);

    // Creates the update operation and sets the update mask.
    $campaignOperation = new CampaignOperation();
    $campaignOperation->setUpdate($campaign);
    $campaignOperation->setUpdateMask(FieldMasks::allSetFieldsOf($campaign));

    // Updates the campaign.
    $campaignServiceClient = $googleAdsClient->getCampaignServiceClient();
    $response = $campaignServiceClient->mutateCampaigns(
        $customerId,
        [$campaignOperation]
    );

    // Displays the results.
    $campaignResourceName = $response->getResults()[0]->getResourceName();
    printf(
        "Updated campaign with resourceName: '%s'.%s",
        $campaignResourceName,
        PHP_EOL
    );
}
      

питон

# Retrieve a new campaign operation
campaign_operation = client.get_type("CampaignOperation")
# Copy the retrieved campaign onto the new campaign operation.
client.copy_from(campaign_operation.update, campaign)
updated_campaign = campaign_operation.update
# Use a page feed to specify precisely which URLs to use with your Dynamic
# Search ads.
updated_campaign.dynamic_search_ads_setting.feeds.append(
    feed_details.resource_name
)
client.copy_from(
    campaign_operation.update_mask,
    protobuf_helpers.field_mask(campaign._pb, updated_campaign._pb),
)

# Retrieve the campaign service.
campaign_service = client.get_service("CampaignService")
# Submit the campaign operation and update the campaign.
response = campaign_service.mutate_campaigns(
    customer_id=customer_id, operations=[campaign_operation]
)
resource_name = response.results[0].resource_name

# Display the results.
print(f"Updated campaign #{resource_name}")
      

Рубин

campaign = result.campaign

op = client.operation.update_resource.campaign(campaign) do
  campaign.dynamic_search_ads_setting.feeds << feed_details.resource_name
end

response = client.service.campaign.mutate_campaigns(
  customer_id: customer_id,
  operations: [op],
)
puts "Updated campaign #{response.results.first.resource_name}"
      

Перл

sub update_campaign_dsa_setting {
  my ($api_client, $customer_id, $feed_details, $campaign_id) = @_;

  # Retrieve the existing dynamic search ads settings for the campaign.
  my $dsa_setting = get_dsa_setting($api_client, $customer_id, $campaign_id);

  my $feed_resource_name = $feed_details->{resourceName};
  $dsa_setting->{feeds} = [$feed_resource_name];

  # Create the campaign object to be updated.
  my $campaign = Google::Ads::GoogleAds::V11::Resources::Campaign->new({
      resourceName =>
        Google::Ads::GoogleAds::V11::Utils::ResourceNames::campaign(
        $customer_id, $campaign_id
        ),
      dynamicSearchAdsSetting => $dsa_setting
    });

  # Create the update operation and set the update mask.
  my $campaign_operation =
    Google::Ads::GoogleAds::V11::Services::CampaignService::CampaignOperation->
    new({
      update     => $campaign,
      updateMask =>
        Google::Ads::GoogleAds::Utils::FieldMasks::all_set_fields_of($campaign)}
    );

  # Update the campaign.
  my $campaigns_response = $api_client->CampaignService()->mutate({
      customerId => $customer_id,
      operations => [$campaign_operation]});

  printf "Updated campaign with resource name: '%s'.\n",
    $campaigns_response->{results}[0]{resourceName};
}
      

Эти настройки сопоставляются с пользовательским интерфейсом Google Ads следующим образом.

use_supplied_urls_only кормит Настройка пользовательского интерфейса Google Рекламы
false Н/Д Используйте индекс Google моего веб-сайта.
false Указывается один или несколько. Используйте URL-адреса как из индекса Google моего веб-сайта, так и из фида моей страницы.
true Указывается один или несколько. Использовать URL-адреса только из фида моей страницы.
true Пустой или null . Не поддерживается. API Google Реклама выдает SettingError.DYNAMIC_SEARCH_ADS_SETTING_AT_LEAST_ONE_FEED_ID_MUST_BE_PRESENT .