如何遍历ID列表以每次为每个ID生成URL?

时间:2020-05-23 11:03:34

标签: python list function loops url

我有一个ID列表,我想通过URL来收集评论中的数据。但是我有点像newb,当我尝试遍历列表时,我只得到一个URL,因此只有一个评论的数据。有人可以解释一下我的代码有什么问题,以及如何获取列表中所有ID的网址并因此收集所有注释的数据吗?

comments_from_reddit = ['fkkmga7', 'fkkgxtj', 'fkklfx3', ...]
def getPushshiftData():
    for ID in range(len(comments_from_reddit)):
        url = 'https://api.pushshift.io/reddit/comment/search?ids={}'.format(comments_from_reddit[ID])
        print(url)
        req = requests.get(url)
        data = json.loads(req.text)
        return data['data']
data = getPushshiftData()

我得到的输出: https://api.pushshift.io/reddit/comment/search?ids=fkkmga7

我非常感谢您对我的问题的任何帮助。感谢您的关注。

1 个答案:

答案 0 :(得分:0)

这应该有效:

comments_from_reddit = ['fkkmga7', 'fkkgxtj', 'fkklfx3', ...]

def getPushshiftData():
    result = list()
    for ID in range(len(comments_from_reddit)):
        url = 'https://api.pushshift.io/reddit/comment/search?ids={}'.format(comments_from_reddit[ID])
        print(url)
        req = requests.get(url)
        data = json.loads(req.text)
        result.append( data['data'] )

    return result

data = getPushshiftData()