Google Search Console 包含大量对技术 SEO 非常有用的信息。但是,使用前端界面可以执行的操作是有限的,并且提取分析所需的数据需要时间。但是,如果您改为通过 Google Search Console API 访问您需要的内容,那么您的生活就会变得更加轻松。
该 API 使您可以直接从 Python 中直接访问您需要的所有数据,因此您可以提取您需要的数据、构建自动化脚本、创建数据管道来操作数据、将其连接到其他来源,以及将数据移动到其他系统中. 这是它的完成方式。
创建服务帐号
要从 Google Search Console API 访问数据,您需要使用 Google API 控制台创建服务帐户并将 JSON 客户端密钥文件下载到您的计算机。这样做的过程有些复杂:
转到Google API Console > Credentials 并选择或创建一个项目。
单击创建凭据 > 服务帐户,填写表单,然后单击创建。
为您的服务帐户用户选择一个角色,即查看者,然后保存。
复制为服务帐户添加的电子邮件地址,即 xxx@xxxx.iam.gserviceaccount.com。
创建一个 JSON 密钥并将其下载到您的机器上。
转到Google Search Console并选择您的资源。
单击设置 > 用户和权限 > 添加用户,然后输入服务帐户电子邮件。
安装软件包
from google.oauth2 import service_account from googleapiclient.discovery import build import requests import json import pandas as pd
为了使 Pandas 数据帧更易于阅读,您可能希望使用pd.set_option('max_colwidth', 150).
pd.set_option('max_colwidth', 150)
存储您的密钥路径
接下来,创建一个名为 key 的变量,并将路径添加到用于在用于 Google Search Console API 的服务帐户上对您进行身份验证的客户端机密 JSON 密钥文件。
key = 'google-search-console.json'
使用您的密钥创建 API 连接
为了处理连接,我们将创建一个基本函数,该函数将key和传递scope给 API 并返回一个可以用来运行查询的服务对象。这对于 Jupyter notebook 使用来说很好,但如果你想在生产中使用它,你需要包含一些错误处理功能。
def connect(key): """Create a connection to the Google Search Console API and return service object. Args: key (string): Google Search Console JSON client secrets path. Returns: service (object): Google Search Console service object. """ scope = ['https://www.googleapis.com/auth/webmasters'] credentials = service_account.Credentials.from_service_account_file(key, scopes=scope) service = build( 'webmasters', 'v3', credentials=credentials ) return service
创建一个函数来运行查询
接下来,我们将创建一个名为的函数query(),该函数接受我们经过身份验证的service对象、site_url标识我们要查询的 Search Console 属性,以及一个payload包含我们的 API 查询的字典。
我们将使用execute()在 API 上运行此查询,然后提取rows,重新格式化数据以使其整洁,并使用 将输出添加到 Pandas 数据帧from_dict()。
def query(service, site_url, payload): """Run a query on the Google Search Console API and return a dataframe of results. Args: service (object): Service object from connect() site_url (string): URL of Google Search Console property payload (dict): API query payload dictionary Return: df (dataframe): Pandas dataframe containing requested data. """ response = service.searchanalytics().query(siteUrl=site_url, body=payload).execute() results = [] for row in response['rows']: data = {} for i in range(len(payload['dimensions'])): data[payload['dimensions'][i]] = row['keys'][i] data['clicks'] = row['clicks'] data['impressions'] = row['impressions'] data['ctr'] = round(row['ctr'] * 100, 2) data['position'] = round(row['position'], 2) results.append(data) return pd.DataFrame.from_dict(results)
运行 Search Console API 查询
最后,我们可以将这些步骤放在一起。我们将通过我们的keytoconnect()来获取一个service对象。我们将创建一个简单的 API 查询payload字典,定义site_url我们要查询的属性,然后使用query(). 这将返回一个我们可以随意操作的 Pandas 数据帧。
service = connect(key) payload = { 'startDate': "2019-01-01", 'endDate': "2019-12-31", 'dimensions': ["page","device","query"], 'rowLimit': 100, 'startRow': 0 } site_url = "https://www.xjqyc.cn" df = query(service, site_url, payload) df.head()
需要完整代码的,关注公众号,回复:googleapi源码demo
发表评论