
在使用stackexchange api进行数据查询时,开发者常会遇到一个常见问题:api响应中仅包含问题的标题(title字段),而缺少详细的问题描述或正文内容(body字段)。这通常是api为了优化数据传输效率和减少负载而采取的默认行为,它只返回最常用的字段。例如,当您尝试获取带有特定标签(如python)的未回答问题时,如果没有特别指定,返回的数据可能不包含正文。
以下是一个初始请求的示例,它可能只会返回问题的标题:
import requests
# 假设已设置 Stack Exchange API key
stack_exchange_api_key = 'your_stack_exchange_api_key'
stack_exchange_endpoint = 'https://api.stackexchange.com/2.3/questions'
stack_exchange_params = {
'site': 'stackoverflow',
'key': stack_exchange_api_key,
'order': 'desc',
'sort': 'creation',
'tagged': 'python',
'answers': 0, # 过滤未回答的问题
}
response = requests.get(stack_exchange_endpoint, params=stack_exchange_params)
if response.status_code == 200:
data = response.json()
for question in data.get('items', []):
print(f"Question Title: {question.get('title')}")
# print(f"Question Body: {question.get('body')}") # 此时 'body' 字段可能缺失或为空
else:
print(f"Error: {response.status_code} - {response.text}")在这种情况下,直接访问question['body']可能会导致KeyError或返回None,因为API默认没有在响应中包含该字段。
要解决仅获取标题的问题并成功检索到问题的完整正文内容,关键在于在StackExchange API请求中添加一个特殊的filter参数。StackExchange API提供了多种预定义的过滤器,其中withbody过滤器专门用于在响应中包含问题的body字段。
通过将'filter': 'withbody'添加到您的请求参数中,API将知道您需要完整的正文内容,并将其包含在返回的JSON数据中。
以下是修改后的API请求参数示例,展示了如何包含withbody过滤器:
import requests
# 假设已设置 Stack Exchange API key
stack_exchange_api_key = 'your_stack_exchange_api_key'
stack_exchange_endpoint = 'https://api.stackexchange.com/2.3/questions'
stack_exchange_params = {
'site': 'stackoverflow',
'key': stack_exchange_api_key,
'filter': 'withbody', # 关键:添加此过滤器以获取问题正文
'order': 'desc',
'sort': 'creation',
'tagged': 'python',
'answers': 0, # 过滤未回答的问题
}
# 发送API请求
response = requests.get(stack_exchange_endpoint, params=stack_exchange_params)
# 检查请求是否成功
if response.status_code == 200:
# 解析响应JSON
data = response.json()
# 遍历问题并打印标题和正文
for question in data.get('items', []):
print(f"Question Title: {question.get('title')}")
print(f"Question Body: {question.get('body')}") # 现在 'body' 字段应该存在了
print("-" * 50) # 分隔线
else:
print(f"Error: {response.status_code} - {response.text}")
通过上述修改,您现在可以轻松地从API响应中获取到每个问题的title和body字段。
当成功应用filter='withbody'参数后,API响应中的每个问题项将包含body字段,其内容通常是HTML格式的问题描述,可能包含代码块、段落标签等。以下是一个典型的输出示例:
Question Title: Is there a way to specify the initial population in optuna's NSGA-II?
Question Body: <p>I created a neural network model that predicts certain properties from coordinates.</p>
<p>Using that model, I want to find the coordinates that minimize the properties in optuna's NSGA-II sampler.</p>
<p>Normally, we would generate a random initial population by specifying a range of coordinates.</p>
<p>However, I would like to include the coordinates used to construct the neural network as part of the initial population.</p>
<p>Is there any way to do it?</p>
<p>The following is a sample code.
I want to include a part of the value specified by myself in the "#" part like x, y = [3, 2], [4.2, 1.4]</p>
<code>import optuna
import matplotlib.pyplot as plt
%matplotlib inline
import warnings
warnings.simplefilter('ignore')
def objective(trial):
x = trial.suggest_uniform("x", 0, 5) #This is the normal way
y = trial.suggest_uniform("y", 0, 3) #This is the normal way
v0 = 4 * x ** 2 + 4 * y ** 2
v1 = (x - 5) ** 2 + (y - 5) ** 2
return v0, v1
study = optuna.multi_objective.create_study(
directions=["minimize", "minimize"],
sampler=optuna.multi_objective.samplers.NSGAIIMultiObjectiveSampler()
)
study.optimize(objective, n_trials=100)
</code>
--------------------------------------------------
# ... 其他问题 ...从上述输出可以看出,Question Body字段包含了完整的HTML格式的问题描述和代码片段。
通过简单地在StackExchange API请求中添加filter='withbody'参数,您可以轻松地从默认仅返回标题的限制中解脱出来,获取到问题的完整正文内容。这对于需要进行深度内容分析、构建问答系统或任何需要完整问题描述的应用程序来说至关重要。理解并有效利用API的过滤器机制,能够极大地提升您数据获取的效率和准确性。
以上就是StackExchange API:获取问题正文内容的完整指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号