需要帮助来优化gspread API调用

时间:2019-06-13 10:35:58

标签: python python-3.x google-sheets-api gspread

我一直在研究gspread来将数据推送到Google表格,并提出了一个可用的python脚本。

此脚本必须执行的“工作”快速背景:

  • 打开Goog​​le表格
  • 从B列读取Instagram用户名
  • 从Instagram收集数据
  • 填写F列中的数据

现在,如上所述,我已经在下面的代码中使用了它。但这确实(至少据我所知)每更新一行使用1个API调用,但是我的工作表将有1000多个带有用户名的行,因此最终可能会使用很多API调用。因此,我更愿意批量进行此操作。因此,临时存储它并在一键中更新所有行。从Gspread文档中,我注意到,如果可以分配确切的单元格和列值,应该有可能,但是我不知道如何建立原始输入数据来简化这一过程。

我的最终用户偶尔也输入空行(上帝知道原因。),但我注意到我当前的逻辑在此处填写数据,实际上需要转到空行下方的行。

因此,我很乐意就如何优化此问题提供意见,并使用当前脚本解决2个“问题”:

  • 减少API调用次数
  • 正确处理空行

这是我的代码:

#import Google 
import gspread
from oauth2client.service_account import ServiceAccountCredentials

#Setting up connection to Google Sheet and picking up the initial values
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('file_init.json',scope)
client = gspread.authorize(creds)
sheet = client.open('Workbookname').sheet1
pp = pprint.PrettyPrinter()

ig_username_column = 2
ig_data_column = 6
ig_usernames = sheet.col_values(ig_username_column)
ig_names = []
i = 2
t = 2
for user in ig_usernames:
    ig_clean = remove_prefix(user,'@')
    ig_names.append(ig_clean)
    print(ig_names)


for name in ig_names[1:]:
    if len(name) != 0:
        print(name)
        ig_url = f'https://www.instagram.com/{name}'
        print(ig_url)
        data = instagram_metrics(ig_url)
        sheet.update_cell(i, ig_data_column, data[2])
        i += 1
    else:
        i += 1 #this is here to skip over empty rows in the Sheet
        continue

    sleep(randint(3,6))

1 个答案:

答案 0 :(得分:1)

  • 您要从“ F”列的第2行中放入值{{1}的data[2]
  • 例如,您要将data = instagram_metrics(ig_url)检索到的18410的{​​{1}}的值放入电子表格。
  • 您希望通过一个API调用将“ 500行”的所有值放入电子表格。

如果我的理解是正确的,那么该修改如何?在此修改中,在for循环中创建了(20, 'username', 18410, 937)。然后,使用instagram_metrics(ig_url)的方法将requests放入电子表格。

修改后的脚本:

请进行如下修改。

从:
request
至:
update_cells()

注意:

  • 我认为在此修改中,可能不需要for name in ig_names[1:]: if len(name) != 0: print(name) ig_url = f'https://www.instagram.com/{name}' print(ig_url) data = instagram_metrics(ig_url) sheet.update_cell(i, ig_data_column, data[2]) i += 1 else: i += 1 #this is here to skip over empty rows in the Sheet continue sleep(randint(3,6))
  • 此修改后的脚本假设您已经能够使用Sheets API写入和读取值。

参考: