首页 > 解决方案 > 每次机器人运行时,如何更新函数的特定参数?

问题描述

我正在使用 gspread 和 IMDbPy 编写一个机器人。脚本现在接受输入(电影标题),然后获取电影 ID,在 IMDB.com 上找到电影的评分,然后将评分发布到电子表格的特定单元格中。

有一个名为“update_cell”的函数,它根据给定的行和列参数更新特定的单元格。机器人完成后,我不想继续进入代码来更新行单元格参数。我希望它在每次机器人执行时更新 1。

有没有办法做到这一点?我将在下面发布代码:

ia = imdb.IMDb()


def take_input():
    fd = open('movielist.txt',"w")
    print("Input your movie please: \n")
    inp = input()
    fd.write(inp)
    fd.close()

take_input()

# Wed 8/28/19 - movie_list is a list object. Must set it equal to our ia.search_movies
# Need to find out where to put movie_list = ia.search_movies in the code, and what to 
# remove or keep.


a = int(52)
b = int(18)



def Main():
    c = """Python Movie Rating Scraper by Nickydimebags"""
    print(c)
    time.sleep(2)
    f1 = open('movielist.txt')
    movie_list = []

    for i in f1.readlines():
        movie_list.append(i)
        movie_list = ia.search_movie(i)
        movie_id = movie_list[0].movieID
        print(movie_id)
        m = ia.get_movie(movie_id)
        print(m)
        rating = m['rating']
        print(rating)
        scope = ["https://spreadsheets.google.com/feeds",'https://www.googleapis.com/auth/spreadsheets',                    "https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive"]
        creds = ServiceAccountCredentials.from_json_keyfile_name("creds.json", scope)
        client = gspread.authorize(creds)
        sheet = client.open("Movie Fridays").sheet1
        sheet.update_cell(a, b, rating) #updates specific cell

Main()

^每次机器人运行时我都需要将a变量更新为 1

标签: pythoniterationbotsgspreadimdbpy

解决方案


我猜 a 变量跟踪行索引。您可以获取要添加值的列中下一个空行单元格的索引。

def next_available_row(worksheet, col):
    return len(worksheet.col_values(col)) + 1


sheet = client.open("Movie Fridays").sheet1
sheet.update_cell(next_available_row(sheet, b), b, rating)

推荐阅读