使用Python和Google Search Console API提交站点地图

时间:2018-03-22 15:45:28

标签: python google-webmaster-tools google-api-python-client google-search-console google-sitemap

我正在编写Python脚本以连续向Search Console提交站点地图。 Python快速启动示例正常工作:https://developers.google.com/webmaster-tools/search-console-api-original/v3/quickstart/quickstart-python

我尝试使用以下代码提交我的站点地图:

CLIENT_ID = 'xxxxx'
CLIENT_SECRET = 'yyyyyy'

OAUTH_SCOPE = 'https://www.googleapis.com/auth/webmasters'

# Redirect URI for installed apps
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'

# Run through the OAuth flow and retrieve credentials
flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI)
authorize_url = flow.step1_get_authorize_url()
print ('Go to the following link in your browser: ' + authorize_url)
code = input('Enter verification code: ').strip()
credentials = flow.step2_exchange(code)

# Create an httplib2.Http object and authorize it with our credentials
http = httplib2.Http()
http = credentials.authorize(http)

webmasters_service = build('webmasters', 'v3', http=http)

WEBSITE = 'http://www.mywebsite.com'
SITEMAP_PATH = 'http://www.mywebsite.com/sitemaps/'
SITEMAPS_LIST = ['sitemap1.xml','sitemap2.xml','sitemap3.xml']

print ('Adding sitemaps to website ' + WEBSITE)
for sitemap in SITEMAPS_LIST:
    print ('  '+SITEMAP_PATH + sitemap)
    webmasters_service.sitemaps().submit(siteUrl=WEBSITE, feedpath=SITEMAP_PATH + sitemap)

没有错误。但站点地图未添加到我的Search Console。 如果我尝试在Search Console中或通过API资源管理器网络界面手动添加文件,那么它就可以正常工作。

1 个答案:

答案 0 :(得分:0)

你可以尝试在语句的最后添加.execute()吗? 像

webmasters_service.sitemaps()。submit(siteUrl = WEBSITE,feedpath = SITEMAP_PATH + sitemap).execute()