Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting link from random article

I have a function that gets the first section of a random Wikipedia article, but I don't know how to get the actual URL of that article. I've looked around in the WikiMedia API and couldn't find it.

getRandomArticle : function() {
    return $.getJSON("http://en.wikipedia.org/w/api.php?action=query&generator=random&grnnamespace=0&prop=extracts&explaintext&exintro=&format=json&callback=?", function (data) {});
}

Any ideas?

like image 565
theintellects Avatar asked May 09 '26 04:05

theintellects


2 Answers

It's not as easy as you might think. The API returns pages with internal ID's, and you have to use the API again to get information on the particular page, such as the URL.

$.getJSON("http://en.wikipedia.org/w/api.php?action=query&generator=random&grnnamespace=0&prop=extracts&explaintext&exintro=&format=json&callback=?", function (data) {
    $.each(data.query.pages, function(k, v) {
        $.getJSON('http://en.wikipedia.org/w/api.php?action=query&prop=info&pageids='+v.pageid+'&inprop=url&format=json&callback=?', function(url) {
            $.each(url.query.pages, function(key, page) {
                console.log(page); // contains the page data
                var url = page.fullurl; // the url to the page
            });
        });
    });
});

FIDDLE

like image 186
adeneo Avatar answered May 11 '26 17:05

adeneo


Your question is similar to What is wikipedia pageid? how to change it into real page url?.

The easiest way? Just go to http://en.wikipedia.org/?curid=pageid.

If you are getting query.result.pageid.extract to get text from the article, then you now the pageid.

like image 23
sheng Avatar answered May 11 '26 17:05

sheng



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!