我一直在玩弄Google,将数据推送到Google表中,并在python中编写了一个工作脚本。
“作业”的快速背景--这个脚本需要做的是:
现在,就像前面说的,我已经在下面的代码中工作了。但这确实使用了(至少在我看来)它更新的每一行都使用了一个API调用,但是我的工作表将有带有用户名的1000+行,因此这可能最终会使用大量的API调用。所以我宁愿散装做这件事。因此,暂时存储它,并在一个大推更新所有行。从Gspread文档中我注意到,如果我能够分配精确的单元格值和列值,那么应该是可能的,但是我不知道如何构建我的原始输入数据以方便这一点。
我的最终用户也偶尔输入空行(天知道为什么.)但我注意到,我的当前逻辑在这里填充了数据,这些数据实际上需要转到空行下面的行。
因此,我很想得到你们对我如何优化这个问题的意见,并用我当前的脚本来解决两个问题:
这是我的密码:
#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))发布于 2019-06-14 00:06:38
data[2] of data = instagram_metrics(ig_url))。18410 of (20, 'username', 18410, 937)的值由instagram_metrics(ig_url)检索到电子表格中。如果我的理解是正确的,这次修改怎么样?在此修改中,将在for循环中创建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))至:
requests = []
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)
requests.append(data[2])
else:
requests.append('')
continue
# Select a range
cell_list = worksheet.range('F2:F' + str(len(requests) + 1))
for i, cell in enumerate(cell_list):
cell.value = requests[i]
# Update in batch
worksheet.update_cells(cell_list)注意:
sleep(randint(3,6))。参考资料:
https://stackoverflow.com/questions/56578624
复制相似问题