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

使用Python代码为Google Search Console添加用户报错求助

解决Google Search Console API添加站点所有者的AttributeError问题

你遇到的AttributeError: 'Resource' object has no attribute 'addOwner'是因为Google Search Console(Webmasters)API v3版本中,sites资源并没有addOwner这个方法。添加站点所有者的正确操作需要通过permissions资源的insert接口实现。

修正后的代码

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

def add_site_owner(site_url, owner_email):
    # 服务账号认证(原代码中的API_KEY未使用,服务账号认证无需API_KEY)
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        'your_service_account_key.json',
        ['https://www.googleapis.com/auth/webmasters']
    )
    service = build('webmasters', 'v3', credentials=credentials, cache_discovery=False)

    # 构建添加所有者的请求:使用permissions.insert方法
    request_body = {
        'emailAddress': owner_email,
        'permissionLevel': 'siteOwner'
    }
    response = service.permissions().insert(
        siteUrl=site_url,
        body=request_body
    ).execute()

    print("Site sahibi başarıyla eklendi:")
    print(response)

if __name__ == "__main__":
    SITE_URL = "YOUR_SITE_URL"  # 格式需为http://或https://开头,比如https://example.com
    OWNER_EMAIL = "site_owner@example.com"

    add_site_owner(SITE_URL, OWNER_EMAIL)

关键修正点

  • 替换方法调用:将原错误的service.sites().addOwner()改为service.permissions().insert(),这是API文档规定的添加权限(包括所有者)的正确接口。
  • 移除无用参数:原代码中的API_KEY未被使用,因为服务账号认证方式不需要API_KEY,直接删除该参数即可。
  • 正确请求体:必须通过body参数传入emailAddress(目标邮箱)和permissionLevel(权限等级,设置为siteOwner表示添加所有者)。

额外注意事项

  • 确保你的服务账号已经被添加为目标站点的现有所有者或具备管理权限,否则无法添加新的所有者。
  • 站点URL格式必须正确,需以http://或https://开头,比如https://yourdomain.com。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 10:43:22