You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Wikipedia API获取特定主题下中等热度的随机条目摘要?

解决方案

要实现获取特定主题下、月浏览量低于10k的随机维基百科条目,需要调整代码逻辑,分为获取主题相关条目、筛选低浏览量条目、随机选择并获取摘要三个核心步骤,具体修改如下:

1. 核心逻辑调整说明

  • 替换原有的完全随机条目获取方式,改用搜索接口获取特定主题相关的条目列表
  • 新增浏览量查询逻辑,调用维基百科的pageviews接口获取条目月浏览量
  • 筛选出月浏览量低于10000的条目,再随机选择一个获取摘要和图片

2. 修改后的完整代码

import requests
import random

def get_wikipedia(topic):
    response = requests.get(f"https://en.wikipedia.org/api/rest_v1/page/summary/{topic}")
    resp = response.json()

    if response.status_code == 200:
        summary = resp.get('extract', '暂无摘要')
        image = resp.get('thumbnail', {}).get('source', '暂无图片')

        print(f"标题: {topic}")
        print(f"摘要: {summary}")
        print(f"图片链接: {image}")
    else:
        print(f"获取{topic}的摘要和图片时出错。")

def get_monthly_views(title):
    # 处理标题中的空格,转换为维基百科URL格式
    encoded_title = title.replace(' ', '_')
    url = f"https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia.org/all-access/user/{encoded_title}/monthly/last-month"
    response = requests.get(url)
    if response.status_code == 200:
        data = response.json()
        if 'items' in data and len(data['items']) > 0:
            return data['items'][0]['views']
    # 若获取失败或无数据,返回None
    return None

def get_target_topic_entries(topic, max_results=50):
    BASE_URL = 'https://en.wikipedia.org/w/api.php'
    params = {
        'format': 'json',
        'action': 'query',
        'generator': 'search',
        'gsrsearch': topic,
        'gsrnamespace': 0,  # 只获取主命名空间条目(排除讨论页等)
        'gsrlimit': max_results,
        'formatversion': 2,
        'utf8': 1
    }
    response = requests.get(BASE_URL, params=params)
    if response.status_code == 200:
        data = response.json()
        if 'query' in data and 'pages' in data['query']:
            return [page['title'] for page in data['query']['pages']]
    return []

# 主逻辑
if __name__ == "__main__":
    target_topic = "Quantum Mechanics"  # 可替换为你需要的特定主题
    # 获取主题相关条目
    related_titles = get_target_topic_entries(target_topic)
    if not related_titles:
        print(f"未找到与{target_topic}相关的条目。")
        exit()
    
    # 筛选月浏览量低于10k的条目
    valid_entries = []
    for title in related_titles:
        views = get_monthly_views(title)
        if views is not None and views < 10000:
            valid_entries.append(title)
    
    if not valid_entries:
        print(f"未找到{target_topic}主题下月浏览量低于10k的条目,可尝试增大搜索结果数量或更换主题。")
    else:
        # 随机选择一个符合条件的条目
        selected_title = random.choice(valid_entries)
        get_wikipedia(selected_title)

3. 关键细节说明

  • 主题相关条目获取:使用generator=search参数,通过关键词搜索获取特定主题的相关条目,可调整max_results参数增加候选条目数量
  • 浏览量查询:调用维基媒体的pageviews接口,获取条目最近一个月的总浏览量
  • 容错处理:增加了对无摘要、无图片、浏览量获取失败等情况的处理,避免程序崩溃

内容的提问来源于stack exchange,提问作者Shounak Das

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 17:31:15