如何迭代一个ID列表,每次为每个ID生成URL?

问题描述 投票:0回答:1

我有一个ID的列表,我想通过URLs来收集评论的数据。但我是个新手,当我试图在列表中迭代时,我只得到一个url,因此只得到一个评论的数据。谁能给我解释一下我的代码有什么问题,如何获取一个列表中所有ID的URL,从而收集所有评论的数据?

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.ioredditcommentsearch?ids=fkkmga7。

我真的会很感激对我问题的任何帮助。谢谢您的关注。

python list function loops url
1个回答
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()
© www.soinside.com 2019 - 2024. All rights reserved.