python 调用 google search console api

目标数据

一、在google search console 注册目标网站

网址:https://search.google.com/search-console/about

要使用 google search console 来监控你的网站,就需要授权给google对应的权限,按照流程一步步走就可以:

二、在google cloud中创建项目

网站:https://cloud.google.com/free/?utm_source=google&utm_medium=cpc&utm_campaign=japac-HK-all-en-dr-BKWS-all-core-trial-EXA-dr-1605216&utm_content=text-ad-none-none-DEV_c-CRE_602321673342-ADGP_Hybrid+%7C+BKWS+-+EXA+%7C+Txt+-GCP-General-core+brand-main-KWID_43700071562408001-aud-970366092687:kwd-6458750523&userloc_9061376-network_g&utm_term=KW_google+cloud&gad_source=1&gclid=CjwKCAjw26KxBhBDEiwAu6KXtwkc0AuMnmUt8KDr1tIfTBXkX1_DEanrdlCJr_QrP7YtgHwhCicLcxoCpqoQAvD_BwE&gclsrc=aw.ds&hl=zh-cn

注册登录账号后,开始创建项目

1. 创建项目

2. 启用google search console api

3. 创建 OAuth 权限请求页面

3.1 app创建、网域添加

3.2 范围权限更新

点击更新,保存继续

3.3 添加测试用户

3.4 生成app摘要,返回信息中心

4. 创建凭据

注意:想要调用 google search console 中的数据,无法通过API密钥获取,我是通过 OAuth客户端获取的。

4.1 创建:桌面应用 客户端

4.2 获取客户端的id和密钥

至此,权限配置基本搞定,开始代码部分的工作。

三、代码开发

1. 安装第三方包

pip install --upgrade google-api-python-client
pip install --upgrade oauth2client

2. 获取刷新令牌

from oauth2client.client import OAuth2WebServerFlow


# 客户端id:修改成你的客户端id
client_id = "apps.googleusercontent.com"
# 密钥:修改成你的客户端密钥
client_secret = "xxx"
# token网站:固定参数,无需修改
oauth_scope = "https://www.googleapis.com/auth/webmasters.readonly"
redirect_uri = 'urn:ietf:wg:oauth:2.0:oob'

# 通过浏览器授权
flow = OAuth2WebServerFlow(client_id, client_secret, oauth_scope, redirect_uri)
authorize_url = flow.step1_get_authorize_url(state=False)
# 点击网址 完成授权操作
print("授权网址: " + authorize_url)
# 输入授权码
auth_code = input("输入授权码:")
credentials = flow.step2_exchange(auth_code)
# 刷新令牌
print('refresh_token:', credentials.refresh_token)
# 访问令牌
print('access_token:', credentials.access_token)

选择你的测试账号

        将授权码输入到代码中,控制台即可得到你的访问令牌,和刷新令牌。访问令牌具备时效性,可以利用刷新令牌来获取新的访问令牌。最重要的是刷新令牌请保存好!!!

3. 创建 search console 客户端

import httplib2
import pandas as pd
from googleapiclient.discovery import build
from oauth2client.client import OAuth2Credentials


def fetch_search_console_data(webmasters_service, website_url, request_body):
    # Initialize an empty list to store the rows from the response
    all_responses = []

    # Initialize the start row to 0
    response_data = webmasters_service.searchanalytics().query(siteUrl=website_url, body=request_body).execute()
    # ?access_token=
    # Append the rows from the response to the all_responses list
    for row in response_data['rows']:
        # Create a temporary list to hold the values for the row
        temp = []
        # Extract the values for the keys (dimensions)
        for key in row['keys']:
            temp.append(key)
        # Extract the values for clicks, impressions, CTR, and position
        temp.append(row['clicks'])
        temp.append(row['impressions'])
        temp.append(row['ctr'])
        temp.append(row['position'])
        # Append the row to the all_responses list
        all_responses.append(temp)
    df = pd.DataFrame(all_responses, columns=request_body['dimensions'] + ['clicks', 'impressions', 'ctr', 'position'])
    return df



# 客户端id:修改成你的客户端id
client_id = "apps.googleusercontent.com"
# 密钥:修改成你的客户端密钥
client_secret = "xxxx"
# token网站:固定参数,无需修改
oauth_scope = "https://www.googleapis.com/auth/webmasters.readonly"
redirect_uri = 'urn:ietf:wg:oauth:2.0:oob'
# 你保存的刷新令牌
refresh_token = 'xxxx'
google_token_url = 'https://oauth2.googleapis.com/token'
credentials = OAuth2Credentials(access_token=None, client_id=client_id,
                                    client_secret=client_secret, refresh_token=refresh_token,
                                    token_expiry=None, token_uri=google_token_url, user_agent=None
                                    )
http = httplib2.Http()
creds = credentials.authorize(http)
# 创建一个searchconsole的客户端
webmasters_service = build('searchconsole', 'v1', http=creds)
# 查询你授权的网址
site_list = webmasters_service.sites().list().execute()
print(site_list)
# 选择你的siteUrl
website_url = 'sc-domain:xxxxx.com'
request_body = {
        "startDate": '2024-04-01',
        "endDate": '2024-04-18',
        "dimensions": ['page'], # 网站页面
        "rowLimit": 1000,
        "dataState": "final",
        'startRow': 0
    }
df = fetch_search_console_data(webmasters_service, website_url, request_body)
df.to_csv('test1.csv',index=False)

4.缺点

1、由于在google cloud中创建的app是测试版本,上述获取的刷新令牌,只有7天的有效期。刷新令牌失效后,也是需要人工再次授权。查略资料说将app上线,从测试版到发布版,然后上述获取刷新令牌的方式就不支持了;

解决方案

通过创建服务账号来获取数据,不涉及人工操作

1. 创建凭据-服务账号

2. 创建密钥

点击后

密钥格式为json,创建好后会自动下载到本地,需要保存好。

3. 给服务账号添加权限

登录google search console 控制台

在这个角色中添加服务账号即可

4. 代码开发

from googleapiclient.discovery import build
import googleapiclient.discovery
from google.oauth2 import service_account



def get_webmasters_service():
    """
    创建一个google search console 的客户端
    :return: web client
    """
    try:
        scopes = ['https://www.googleapis.com/auth/webmasters.readonly']
        service_account_file = '服务账号生成的密钥文件存放路径'
        credentials = service_account.Credentials.from_service_account_file(service_account_file, scopes=scopes)
        webmasters_service = googleapiclient.discovery.build('searchconsole', 'v1',
                                                             credentials=credentials,
                                                             cache_discovery=False)
        return webmasters_service
    except Exception as e:
        print(e)

笑死,看着这么少的代码,我也是服了,毕竟对于谷歌的产品也是第一次使用,很多不了解,绕了不少路。

参考资料

youtube:https://www.youtube.com/watch?v=ptWJkrd0vqc&t=59s

官方文档:https://developers.google.com/webmaster-tools/about?hl=zh-cn

OAuth 授权:https://developers.google.com/identity/protocols/oauth2/web-server?hl=zh-cn#creatingclient

  • 10
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值