什么是生成器?

可以使用生成器来添加实体。 每个父对象(如 Campaign)都包含用于获取用于添加子实体的构建器对象的方法。 例如,要向市场活动添加广告组,你需要调用 Campaign 对象的方法 newAdGroupBuilder

builder 对象包括用于设置实体属性值的方法。 例如,要指定关键字 (keyword) 的 CPC,可以使用此withCpc方法。 设置实体的所有属性值后,将调用 build 创建实体的方法。 生成过程是一个异步过程,其中请求与其他生成请求一起排队并批量处理。 批处理请求将在脚本终止前完成。

要确定生成请求是否成功,可以查看日志,也可以使用该方法返回的操作对象 build 。 例如, AdGroupBuilder 返回 AdGroupOperation。 您可以调用操作对象的任何方法 (isSuccessful,或) 来 getResultgetErrors 确定脚本是否成功创建了实体。 但是,调用这些方法时存在性能注意事项 (请参阅 性能注意事项) 。

下面的示例从概念上演示如何使用 builder 和 operation 对象创建关键字 (keyword) 。 可能仅当创建单个实体 (或几个) 时才应使用此流。

    // Gets the first ad group in the account.
    var adGroup = AdsApp.adGroups().get().next();

    // Use the 'with' methods to specify the keyword's property values.
    // The .build() method adds the build request to the build queue.
    var keywordOperation = adGroup.newKeywordBuilder()
        .withCpc(1.2)
        .withText("shirts")
        .withFinalUrl("https://www.contoso.com/shirts")
        .build();

    // Call isSuccessful() to determine if the build succeeded.
    // Calling any of the operation object's method processes the
    // build request immediately. 
    if (keywordOperation.isSuccessful()) {
        // You only need to call getResult if you need to access
        // the new keyword entity.
        var keyword = keywordOperation.getResult();
    } else {
        // Handle the errors.
        for (var error of keywordOperation.getErrors()) {
            Logger.log(`${error}\n`);
        }
    }

性能注意事项

为了提高性能,脚本会批量处理生成请求。 如果调用生成请求的操作方法,它会强制脚本立即处理排队的生成请求,从而抵消任何性能提升。 如果要创建多个实体,请不要在用于生成实体的同一循环中执行操作方法。 这会导致性能不佳,因为一次只处理一个实体。 相反,请创建一个操作数组,并在生成循环后处理它们。

具体操作

    // An array to hold the operations, so you 
    // can process them after all the entities are queued.
    var operations = []; 

    // Create all the new entities.
    for (var i = 0; i < keywords.length; i++) {
        var keywordOperation = AdsApp.adGroups().get().next()
          .newKeywordBuilder()
          .withText(keywords[i])
          .build();
        operations.push(keywordOperation);
    }

    // Now call the operation method so the build requests
    // get processed in batches.
    for (var i = 0; i < operations.length; i++) {
        var newKeyword = operations[i].getResult();
    }

请勿执行此操作

    for (var i = 0; i < keywords.length; i++) {
        var keywordOperation = AdsApp.adGroups().get().next()
          .newKeywordBuilder()
          .withText(keywords[i])
          .build();

        // Don't get results in the same loop that creates
        // the entity because Scripts then only processes one
        // entity at a time.
        var newKeyword = keywordOperation.getResult();
    }

以下是生成器列表。

后续步骤