admin管理员组文章数量:1530984
目标数据
一、在google search console 注册目标网站
网址:https://search.google/search-console/about
要使用 google search console 来监控你的网站,就需要授权给google对应的权限,按照流程一步步走就可以:
二、在google cloud中创建项目
网站:https://cloud.google/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"
# 密钥:修改成你的客户端密钥
client_secret = "xxx"
# token网站:固定参数,无需修改
oauth_scope = "https://www.googleapis/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"
# 密钥:修改成你的客户端密钥
client_secret = "xxxx"
# token网站:固定参数,无需修改
oauth_scope = "https://www.googleapis/auth/webmasters.readonly"
redirect_uri = 'urn:ietf:wg:oauth:2.0:oob'
# 你保存的刷新令牌
refresh_token = 'xxxx'
google_token_url = 'https://oauth2.googleapis/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'
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/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/watch?v=ptWJkrd0vqc&t=59s
官方文档:https://developers.google/webmaster-tools/about?hl=zh-cn
OAuth 授权:https://developers.google/identity/protocols/oauth2/web-server?hl=zh-cn#creatingclient
本文标签: GooglePythonSearchAPIConsole
版权声明:本文标题:python 调用 google search console api 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dongtai/1725992621a1051673.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论