Skip to main content
 首页 » 编程设计

python之堆栈交换 API : fetch answers to a specific stack post

2025年05月04日13qq78292959

我正在使用 stackAPI与 stackexchange api 接口(interface)的 Python 包装器。我正在尝试获取超过投票计数阈值的 HitTest 门问题;对于每个问题,超过一定票数的请您参考如下方法:将被计入。

  SITE = StackAPI("stackoverflow") 
  SITE.max_pages=2 
  SITE.page_size=100 
  questions = SITE.fetch('questions', min=10, sort='votes') 
  for quest in questions['items']: 
    if 'title' not in quest: continue 
    quest_id = quest['question_id'] 
    title = quest['title'] 
    tags = [] 
    if 'tags' in quest: 
      tags = quest['tags'] 
    #body = quest['body'] 
    body = "" 
    if 'body' in quest: 
      body = quest['body'] 
 
    answers = SITE.fetch('answers', id=[quest_id],min=10, sort='votes') 
    for answer in answers['items']: 
         _stuck here_ 

这是我卡住的地方,如何获取上述 question_id 的答案 此查询返回一些随机的 answer_id。如何获取 question-< answers

请您参考如下方法:

我修改了您的代码以获得像这样的最高投票答案。

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(top_answer) 

如果您想获得该问题的可接受答案,您可以通过以下方式获得:-

accepted_answer_id = quest['accepted_answer_id'] 
print('Accepted Answer ID :- {0}'.format(accepted_answer_id)) 

Stackoverflow 使用此 id 作为下面的示例来生成该答案的 url,如下所示:-

answer = "https://stackoverflow.com/a/" + str(accepted_answer_id) 
print(answer) 

希望对你有帮助!