I'm trying to pull a random article from the WikiMedia API, but my code seems to only grab User talk pages...
$(document).ready(function(){
$.getJSON("http://en.wikipedia.org/w/api.php?action=query&generator=random&prop=extracts&exchars=500&format=json&callback=?", function (data) {
console.log(data.query.pages);
});
});
I read that "generator=random" pulls a random article, but that does not seem to be the case. How do I get it working as intended?
If you want to get only pages in namespace 0, you need to specify the rnnamespace
parameter. And since you're using list=random
as a generator, it's spelled as grnnamespace
:
The API does not allow you to directly get random pages; the random generator currently gets random pages from any namespace. EDIT: I stand corrected; apparently you can by passing in a grnamespace
parameter, as svick mentions in their answer. I'll leave my original answer below though.
How about making two API calls?
First, make a call to grab a list of random pages:
https://en.wikipedia.org/w/api.php?action=query&list=random&rnnamespace=0&rnlimit=5&format=json
Adjust the rnlimit
parameter based on how many pages you want.
To get the wiki-source, use the following (replacing TITLE1, TITLE2, etc. with your actual titles):
https://en.wikipedia.org/w/api.php?action=query&titles=TITLE1|TITLE2&prop=revisions&rvprop=content&format=json
For an HTML copy of the pages, use the following (replacing TITLE with your actual title, and calling the API repeatedly):
https://en.wikipedia.org/w/api.php?action=parse&page=TITLE&prop=text&format=json
Of course, it might just be easier to call Special:Random directly, and screen-scrape:
https://en.wikipedia.org/wiki/Special:Random
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With