You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Google Analytics API批量获取指定页面标题的页面指标?

Hey there! Glad to hear your initial GA Core Reporting API v4 Python setup is working smoothly. Let’s break down exactly how to batch query those page title metrics efficiently—no need to wade through the dense official docs alone.

Core Guidance for Batch Querying Page Title Metrics

1. Adjust the Core Query Structure

Your existing quickstart code includes a report_requests object—this is where you’ll define what data to pull. Here’s what to tweak:

  • Dimensions: Add ga:pageTitle to group results by page title.
  • Metrics: Specify the exact metrics you need: ga:pageviews (page views) and ga:avgTimeOnPage (average time on page).
  • Filtering: Target your list of page titles directly using an IN operator in the filter expression.

Example modified request snippet:

report_requests = [
    {
        'viewId': 'YOUR_VIEW_ID',  # Replace with your actual view ID
        'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}],  # Adjust date range as needed
        'metrics': [
            {'expression': 'ga:pageviews'},
            {'expression': 'ga:avgTimeOnPage'}
        ],
        'dimensions': [{'name': 'ga:pageTitle'}],
        # Filter for your target page titles (match exact GA values)
        'filtersExpression': 'ga:pageTitle IN ("首页 - 我的网站", "产品列表页", "关于我们")'
    }
]

2. Handle Long Page Title Lists

If your list has dozens of titles (too long for a single filter), split it into smaller chunks to avoid API errors:

  • Split your list into groups (e.g., 20 titles per chunk—test to find the optimal size for your use case).
  • Loop through each chunk, generate a new filter expression for each, and run separate queries.

Example chunking code:

def split_title_list(title_list, chunk_size):
    # Split list into smaller batches
    for i in range(0, len(title_list), chunk_size):
        yield title_list[i:i+chunk_size]

# Your full list of target page titles
target_titles = ["首页 - 我的网站", "产品列表页", "关于我们", ...]

# Process each chunk
for title_chunk in split_title_list(target_titles, 20):
    # Build filter expression for the current chunk
    filter_str = f'ga:pageTitle IN ({",".join([f'"{title}"' for title in title_chunk])})'
    # Update your report request with this filter and execute the query
    # (Reuse your existing API call logic here)

3. Parse Results into a Usable Dataset

The API returns nested JSON—convert it into a structured format like a CSV or Pandas DataFrame for your dataset:

import pandas as pd

def parse_ga_response(response):
    # Extract headers (dimensions + metrics)
    report = response.get('reports', [])[0]
    dim_headers = [h['name'] for h in report.get('columnHeader', {}).get('dimensions', [])]
    metric_headers = [m['name'] for m in report.get('columnHeader', {}).get('metricHeader', {}).get('metricHeaderEntries', [])]
    all_headers = dim_headers + metric_headers

    # Extract row data
    rows = report.get('data', {}).get('rows', [])
    data_rows = []
    for row in rows:
        row_data = row.get('dimensions', [])
        row_data += row.get('metrics', [])[0].get('values', [])
        data_rows.append(row_data)
    
    # Return as a DataFrame
    return pd.DataFrame(data_rows, columns=all_headers)

# Combine results from all chunks into one dataset
full_dataset = pd.DataFrame()
for title_chunk in split_title_list(target_titles, 20):
    # Build and execute query
    report_requests[0]['filtersExpression'] = f'ga:pageTitle IN ({",".join([f'"{title}"' for title in title_chunk])})'
    response = analytics.reports().batchGet(body={'reportRequests': report_requests}).execute()
    # Parse and append to full dataset
    chunk_df = parse_ga_response(response)
    full_dataset = pd.concat([full_dataset, chunk_df], ignore_index=True)

# Save to CSV for your dataset
full_dataset.to_csv('page_title_metrics.csv', index=False)

4. Key Tips to Avoid Headaches

  • Exact Matches: Ensure your page titles match exactly what’s stored in GA (including capitalization, special characters, and spacing). If unsure, run a quick unfiltered query to pull all existing page titles first.
  • API Quotas: GA v4 has rate limits (10 requests/second, 10,000 requests/day). Batch queries in reasonable chunks to stay within limits.
  • Date Range Flexibility: Use absolute dates (e.g., '2024-01-01') or relative dates (e.g., '30daysAgo') based on your dataset needs.

内容的提问来源于stack exchange,提问作者Tree

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 09:42:36