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

使用Python调用Google Analytics userActivity.search获取用户数据报错求助

Fixing the "method() takes 1 positional argument but 2 were given" Error in Google Analytics User Activity API

I’ve run into this exact issue before—here’s what’s going wrong and how to fix it:

Why the Error Occurs

The error pops up because you’re passing the request body directly as a positional argument to the search() method, but the Google Client Library for Python expects the request body to be specified using the body keyword parameter. Unlike some other API methods, userActivity().search() doesn’t accept the body as a positional argument.

You need to explicitly pass your request object using the body= keyword, just like you did with batchGet() in the original quickstart. Here’s a complete working example:

from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

# Authenticate (same as your existing setup)
SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
KEY_FILE_LOCATION = 'path/to/your/service-account-key.json'
VIEW_ID = 'your-view-id-here'

credentials = ServiceAccountCredentials.from_json_keyfile_name(
    KEY_FILE_LOCATION, SCOPES)
analytics = build('analyticsreporting', 'v4', credentials=credentials)

# Build your User Activity request body
user_activity_request = {
    "viewId": VIEW_ID,
    "user": {
        "userId": "target-user-id"  # Use userIp instead if you don't have a userId
    },
    "dateRange": {
        "startDate": "2024-01-01",
        "endDate": "2024-01-31"
    },
    "pageSize": 10  # Optional: adjust how many activities to retrieve
}

# Correct call to search() with body keyword parameter
response = analytics.userActivity().search(body=user_activity_request).execute()

# Print or process the response
print(response)

Alternative Approach: Build the Request Explicitly

If you prefer a more verbose (but sometimes clearer) approach, you can build the request object first and set its body before executing:

request = analytics.userActivity().search()
request.body = user_activity_request
response = request.execute()

Key Takeaway

Always remember to use the body= keyword when passing request payloads to Google Analytics API methods that require it. The original batchGet() example works because it uses body=request—you just need to apply the same pattern to userActivity().search().

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:53:03