获取维基百科文章,排除列表中包含标题的文章

时间:2014-01-31 17:14:37

标签: javascript wikipedia-api

所以我想获得随机的维基百科文章,但我不想抓住标题或类别在我所拥有的特定列表中的那些(用于坏词过滤)。

我目前正在使用javascript而且我对维基百科API不太熟悉但是我有查询字符串来生成一篇随机文章并获取摘录但我不太清楚如何进行排除。我没有在文档中看到任何内容,甚至没有在Google上搜索如何执行此操作。

代码正在运行并且正在获取随机文章,但我需要过滤它们。

我提取的实际javascript代码

if (tempscript) return;
        if (!isRetry) {
            attempts = 0;
            minchars = minimumCharacters;
            maxchars = maximumCharacters;
            button.disabled = true;
            button.style.cursor = "wait";
        }
        tempscript = document.createElement("script");
        tempscript.type = "text/javascript";
        tempscript.id = "tempscript";
        tempscript.src = "http://en.wikipedia.org/w/api.php" + "?action=query&generator=random&prop=extracts" + "&exchars=" + maxchars + "&format=json&callback=onComplete&requestid=" + Math.floor(Math.random() * 999999).toString();
        document.body.appendChild(tempscript);

1 个答案:

答案 0 :(得分:1)

您应该将您的网址更改为categories中的prop,然后将cllimit设置为最大值500:

tempscript.src = "http://en.wikipedia.org/w/api.php" + "?action=query&generator=random&prop=categories|extracts&cllimit=500&exchars=" + maxchars + "&format=json&callback=onComplete&requestid=" + Math.floor(Math.random() * 999999).toString();

然后,如果页面有类别,它将在返回的JSON对象中列出它们。

在回调函数中,您将需要以下内容:

var badArticles = ['Poop', 'Pee', 'Underpants'],
    badCategories = ['Images of poop', 'Images of pee', 'Images of underpants'],
    page = response.query.pages;
for (var i in page) {
    page = page[i]; // `i` will be the pageid in this loop
    break; // you don't want the loop to continue within the new `page` object
}

//exit callback when pagename is in bad articles list 
if (badArticles.indexOf(page.title) !== -1) return false;

if (page.categories) {
    for (var i=0;i<page.categories.length;i++) {

        //exit callback when pagename has a category in bad categories list
        if (badCategories.indexOf(page.categories[i].title)) return false;

    }
}

那应该有用。我没有亲自测试它,但我希望这可以工作,基于MediaWiki API的响应格式。如果这不起作用,请发表评论。