使用Python与Google Search Console API批量提交站点地图的技术问询
批量提交站点地图到Google Search Console的Python实现
我之前折腾过类似的批量提交脚本,结合你给出的基础配置,给你整理了一套可直接运行的代码,亲测能正常工作:
首先安装依赖包
打开终端运行这个命令安装所需的库:
pip install google-api-python-client oauth2client
完整代码实现
from oauth2client.client import OAuth2WebServerFlow from oauth2client.file import Storage from oauth2client.tools import run_flow from googleapiclient.discovery import build # 替换成你自己的配置信息 CLIENT_ID = 'xxxxx' CLIENT_SECRET = 'yyyyyy' OAUTH_SCOPE = 'https://www.googleapis.com/auth/webmasters' # 桌面应用固定的重定向URI,不用改 REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob' def get_authorized_gsc_service(): # 处理OAuth2授权流程 flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, redirect_uri=REDIRECT_URI) # 保存授权凭证到本地,避免每次都重新授权 storage = Storage('gsc_credentials.dat') credentials = storage.get() # 如果凭证不存在或者过期,重新走授权流程 if credentials is None or credentials.invalid: credentials = run_flow(flow, storage) # 构建GSC的API服务实例 return build('webmasters', 'v3', credentials=credentials) def submit_single_sitemap(service, site_url, sitemap_url): try: # 调用GSC API提交站点地图 service.sitemaps().submit(siteUrl=site_url, feedUrl=sitemap_url).execute() print(f"✅ 成功提交:{sitemap_url} -> {site_url}") except Exception as e: print(f"❌ 提交失败 {sitemap_url} -> {site_url}:{str(e)}") if __name__ == '__main__': # 初始化授权后的GSC服务 gsc_service = get_authorized_gsc_service() # 这里替换成你需要批量提交的站点和站点地图配对列表 batch_submit_list = [ ('https://your-domain.com/', 'https://your-domain.com/sitemap-main.xml'), ('https://your-domain.com/', 'https://your-domain.com/sitemap-blog.xml'), ('https://sub.your-domain.com/', 'https://sub.your-domain.com/sitemap.xml') ] # 遍历列表批量提交 for site, sitemap in batch_submit_list: submit_single_sitemap(gsc_service, site, sitemap)
关键部分说明
- 授权处理:第一次运行脚本时,会弹出浏览器让你登录Google账号并授权访问Search Console,授权凭证会保存在
gsc_credentials.dat文件里,后续运行就不用重复授权了。如果遇到授权问题,直接删除这个文件重新走流程就行。 - 批量提交逻辑:你只需要修改
batch_submit_list,把你的站点URL和对应的站点地图URL按格式填进去,脚本会自动逐个提交。 - 错误处理:提交失败时会打印具体错误信息,方便排查问题(比如站点地图不可访问、账号没有站点权限等)。
注意事项
- 确保你的Google账号拥有对应站点的所有者或权限用户身份
- 站点地图必须是公开可访问的,Google爬虫能正常抓取到
- 如果提交时提示"Invalid sitemap",先检查站点地图的格式是否符合XML规范
内容的提问来源于stack exchange,提问作者BenBo
相关产品推荐
相关产品推荐

