首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何解决Google Indexing API内部循环问题?

如何解决Google Indexing API内部循环问题?
EN

Stack Overflow用户
提问于 2021-10-20 16:39:56
回答 1查看 70关注 0票数 0

我有一个谷歌索引API代码的工作。代码如下:

代码语言:javascript
复制
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.')

我可以用它一个接一个地添加URL,但我想给它提供一个CSV文件,这样它就可以逐行读取并发送到谷歌。

我创建了以下代码:

代码语言:javascript
复制
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。我是编程新手,所以不要对我苛刻:)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-10-20 16:46:38

将一条print(content)语句放入for循环中,我想您会发现它并没有包含您认为它所做的事情。整个字符串就是您在那里键入的文字内容。

你需要这样的东西:

代码语言:javascript
复制
        content = f"""{{ 
        "url": {row[0]}, 
        "type": "URL_UPDATED" 
        }}""" 

f"""创建一个字符串插值,在其中对{}中的内容进行求值。然后,您需要使用{{}}来获得文字大括号。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69649927

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档