Python3.8使用OAuth2认证调用谷歌API出现HTTPError 403如何解决?
Google Search Console API 403错误解决方案
错误场景1:站点权限不足报错
报错提示:
User does not have sufficient permission for site 'XXXXXXXX.com'
排查步骤
- 确认OAuth授权时使用的谷歌账号,已被添加至对应站点的Google Search Console后台,权限等级至少为只读
- 核对API请求中传入的站点URL,与Search Console后台添加的站点前缀完全匹配:需严格对应http/https协议、www/非www前缀,二者不一致会直接触发权限校验失败
- 如果你使用的是Search Console域名属性(Domain Property),请求时站点参数需添加
sc-domain:前缀,格式为sc-domain:你的域名,不可直接填写域名
错误场景2:无Google Analytics账号权限报错
解决步骤
- 现有代码的授权范围仅配置了Search Console只读权限,如果请求的接口需要关联拉取GA数据,需要在
SCOPES列表中新增Google Analytics对应权限,调整后需删除本地已生成的authorizedcreds.dat缓存文件,重新发起OAuth授权获取新凭证 - 确认授权的谷歌账号同时拥有对应Google Analytics账号的访问权限,权限需与GSC站点权限匹配
现有代码说明
你提供的授权逻辑本身无功能性问题,唯一需要注意的是:
只要调整过账号权限、授权范围,必须先删除本地存储的authorizedcreds.dat凭证缓存文件,否则程序会一直复用旧的权限不足的凭证,持续触发403错误。
def get_domain_name(start_url): domain_name = '{uri.netloc}'.format(uri=urlparse(start_url)) # Get Domain Name To Name Project domain_name = domain_name.replace('.','_') return domain_name def create_project(directory): if not os.path.exists(directory): print('Create project: '+ directory) os.makedirs(directory) def authorize_creds(creds): # Variable parameter that controls the set of resources that the access token permits. SCOPES = ['https://www.googleapis.com/auth/webmasters.readonly'] # Path to client_secrets.json file CLIENT_SECRETS_PATH = creds # Create a parser to be able to open browser for Authorization parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, parents=[tools.argparser]) flags = parser.parse_args([]) flow = client.flow_from_clientsecrets( CLIENT_SECRETS_PATH, scope = SCOPES, message = tools.message_if_missing(CLIENT_SECRETS_PATH)) # Prepare credentials and authorize HTTP # If they exist, get them from the storage object # credentials will get written back to a file. storage = file.Storage('authorizedcreds.dat') credentials = storage.get() # If authenticated credentials don't exist, open Browser to authenticate if credentials is None or credentials.invalid: credentials = tools.run_flow(flow, storage, flags) http = credentials.authorize(http=httplib2.Http()) webmasters_service = build('webmasters', 'v3', http=http) return webmasters_service
内容的提问来源于stack exchange,提问作者J_dev42
相关产品推荐
相关产品推荐

