我有一個有效的 Google 索引 API 代碼。代碼如下:
from oauth2client.service_account import ServiceAccountCredentials
import httplib2
SCOPES = ["https://www.googleapis.com/auth/indexing"]
ENDPOINT = "https://indexing.googleapis.com/v3/urlNotifications:publish"
# service_account_file.json is the private key
# that you created for your service account.
JSON_KEY_FILE = "/content/astute-tractor-329613-1baed60ec1c0.json"
credentials = ServiceAccountCredentials.from_json_keyfile_name(JSON_KEY_FILE, scopes=SCOPES)
http = credentials.authorize(httplib2.Http())
content = """{
"url": "https://sitename.com/index.php",
"type": "URL_UPDATED"
}"""
response, content = http.request(ENDPOINT, method="POST", body=content)
if response.status == 200:
print(f'The submission was successful. Google reported a {response.status} response code.')
else:
print(f'The submission was not successful. Google reported a {response.status} response code, instead of 200.')
我可以用它一個一個地添加網址,但我想給它提供一個CSV檔案,這樣它就可以一行一行地讀取它并將其發送給谷歌。
我創建了以下代碼:
from oauth2client.service_account import ServiceAccountCredentials
import httplib2
import csv
SCOPES = ["https://www.googleapis.com/auth/indexing"]
ENDPOINT = "https://indexing.googleapis.com/v3/urlNotifications:publish"
# service_account_file.json is the private key
# that you created for your service account.
JSON_KEY_FILE = "/content/astute-tractor-329613-1baed60ec1c0.json"
credentials = ServiceAccountCredentials.from_json_keyfile_name(JSON_KEY_FILE, scopes=SCOPES)
http = credentials.authorize(httplib2.Http())
with open('/content/indekseerida-1.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
for row in readCSV:
content = """{
"url": row[0],
"type": "URL_UPDATED"
}"""
response, content = http.request(ENDPOINT, method="POST", body=content)
if response.status == 200:
print(f'The submission was successful. Google reported a {response.status} response code.')
else:
print(f'The submission was not successful. Google reported a {response.status} response code, instead of 200.')
這僅給我回傳錯誤回應代碼 400。我對編碼很陌生,所以不要對我苛刻:)
uj5u.com熱心網友回復:
print(content)在你的 for 回圈中放入一個陳述句,我想你會發現它不包含你認為的內容。整個字串只是你在那里輸入的文字內容。
你需要這樣的東西:
content = f"""{{
"url": {row[0]},
"type": "URL_UPDATED"
}}"""
將f"""創建一個字串插在其內側里面的東西{}進行評估。然后你需要{{and}}獲得文字大括號。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/329235.html
標籤:Python for循环 http-status-code-400 google-indexing-api
上一篇:減少和列印字串陣列
下一篇:提高For回圈限制
