如何使用 Stack Exchange API 获取答案的正文?

我正在使用StackAPI来获得投票最多的问题和这些问题的投票最多的答案:-


from stackapi import StackAPI

SITE = StackAPI('stackoverflow')

SITE.max_pages=1

SITE.page_size=10


questions = SITE.fetch('questions', min=20, tagged='python', sort='votes')

for quest in questions['items']:

    if 'title' not in quest or quest['is_answered'] == False:

        continue

    title = quest['title']

    print('Question :- {0}'.format(title))

    question_id = quest['question_id']

    print('Question ID :- {0}'.format(question_id))

    top_answer = SITE.fetch('questions/' + str(question_id) + '/answers', order = 'desc', sort='votes')

    print('Most Voted Answer ID :- {0}'.format(top_answer['items'][0]['answer_id']))

现在使用这个answer_id我想得到那个答案的正文。我可以通过使用此 API 链接获取其余详细信息。


翻阅古今
浏览 283回答 1
1回答

慕标琳琳

您需要使用自定义过滤器来获取问题/答案/帖子正文。好消息是,您还可以使用自定义过滤器在获取问题的同时获取答案数据——无需再调用 API。例如,如果您/questions使用过滤器调用路由:    !*SU8CGYZitCB.D*(BDVIficKj7nFMLLDij64nVID)N9aK3GmR9kT4IzT*5iO_1y3iZ)6W.G*你得到的结果如下:"items": [ {&nbsp; &nbsp; "tags": ["python", "iterator", "generator", "yield", "coroutine"],&nbsp; &nbsp; "answers": [ {&nbsp; &nbsp; &nbsp; &nbsp; "owner": {"user_id": 8458, "display_name": "Douglas Mayle"},&nbsp; &nbsp; &nbsp; &nbsp; "is_accepted": false,&nbsp; &nbsp; &nbsp; &nbsp; "score": 248,&nbsp; &nbsp; &nbsp; &nbsp; "creation_date": 1224800643,&nbsp; &nbsp; &nbsp; &nbsp; "answer_id": 231778,&nbsp; &nbsp; &nbsp; &nbsp; "body": "<p><code>yield</code> is just like <code>return</code> - it returns what..."&nbsp; &nbsp; &nbsp; &nbsp; }, {&nbsp; &nbsp; &nbsp; &nbsp; "owner": {"user_id": 22656, "display_name": "Jon Skeet"},&nbsp; &nbsp; &nbsp; &nbsp; "is_accepted": false,&nbsp; &nbsp; &nbsp; &nbsp; "score": 139,&nbsp; &nbsp; &nbsp; &nbsp; "creation_date": 1224800766,&nbsp; &nbsp; &nbsp; &nbsp; "answer_id": 231788,&nbsp; &nbsp; &nbsp; &nbsp; "body": "<p>It's returning a generator. I'm not particularly familiar with Python, ..."&nbsp; &nbsp; &nbsp; &nbsp; }, {&nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; } ],&nbsp; &nbsp; "owner": {"user_id": 18300, "display_name": "Alex. S."},&nbsp; &nbsp; "is_answered": true,&nbsp; &nbsp; "accepted_answer_id": 231855,&nbsp; &nbsp; "answer_count": 40,&nbsp; &nbsp; "score": 8742,&nbsp; &nbsp; "creation_date": 1224800471,&nbsp; &nbsp; "question_id": 231767,&nbsp; &nbsp; "title": "What does the &quot;yield&quot; keyword do?"&nbsp; &nbsp; },&nbsp; &nbsp; ...所以,改变这个:questions = SITE.fetch('questions', min=20, tagged='python', sort='votes')对于这样的事情:questions = SITE.fetch('questions', min=20, tagged='python', sort='votes', filter='!*SU8CGYZitCB.D*(BDVIficKj7nFMLLDij64nVID)N9aK3GmR9kT4IzT*5iO_1y3iZ)6W.G*')然后相应地调整你的for循环。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python