Public
Script
October 23, 2023
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { fetch } from "https://esm.town/v/std/fetch";
export const getRandomArticleInCategory = async (category) => {
try {
if (!category) {
throw new Error("Invalid input. Please provide a category as a string.");
}
const { DOMParser } = await import(
"https://deno.land/x/deno_dom/deno-dom-wasm.ts"
);
// Replace spaces with underscores in the category name, and URL encode it
const encodedCategory = encodeURIComponent(category.replace(/ /g, "_"));
const listUrl =
`https://en.wikipedia.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:${encodedCategory}&cmlimit=500&format=json&origin=*`;
const listResponse = await fetch(listUrl);
const listData = await listResponse.json();
if (!listData.query.categorymembers.length) {
throw new Error(`No Wikipedia articles found in category "${category}"`);
}
// Get a random article from the list
const randomArticle =
listData.query
.categorymembers[
Math.floor(Math.random() * listData.query.categorymembers.length)
].title;
const contentUrl =
`https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exintro&titles=${
encodeURIComponent(randomArticle)
}&format=json&utf8=1&origin=*`;
const contentResponse = await fetch(contentUrl);
const contentData = await contentResponse.json();
const pageId = Object.keys(contentData.query.pages)[0];
const textContent = contentData.query.pages[pageId].extract;
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(textContent, "text/html");
const extractedText = htmlDoc.querySelector("body").textContent;
return `${extractedText.trim()}`;
}
catch (error) {
console.log("Error fetching Wikipedia content:", error);
return `An error occurred while fetching the Wikipedia content. ${error}`;
}
};
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
October 23, 2023