-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
56 lines (52 loc) · 1.72 KB
/
index.js
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
44
45
46
47
48
49
50
51
52
53
54
55
56
import cheerio from "cheerio"
export default class QuizletFetcher {
/**
* Create a Quizlet Parser
* @param {string} html - The HTML string to parse.
* @throws {Error} Will throw an error if the HTML is not a string.
*/
constructor(html) {
if (!html || typeof html !== "string") {
throw new Error("Please provide a string of HTML!");
}
const $ = cheerio.load(html)
this.$ = $
var obj = {};
obj.title = $("title").text().replace(" Flashcards | Quizlet", "").replace("Back ButtonSearch IconFilter Icon", "");
if ($(".SetPageHeader-description")[0]) obj.description = $(".SetPageHeader-description")[0].children[0].data
obj.author = $(".UserLink-username--typography-subheading-3").text()
var cards = [];
var i = 0;
var y = 0;
while (i < $(".TermText").length) {
if (i % 2 == 0) {
cards.push({ term: $(".TermText")[i].children[0].data });
} else {
cards[y].definition = $(".TermText")[i].children[0].data;
y++;
}
i++;
}
i = 0
while (i < $(".SetPageTerm-image").length) {
var term = $(".SetPageTerm-image")[i].attribs.alt.replace("Image: ", "")
var src = $(".SetPageTerm-image")[i].attribs.src
var card = cards.find(card => card.term === term);
if (card) {
card.image = src;
card.sourceImage = src.replace(/^https:\/\/.*?\/(https?:\/\/.*)$/, "$1")
}
i++
}
obj.cards = cards;
this.html = html
this.json = obj
}
/**
* Get the JSON of a Quizlet set
* @return {{title: string, description: string, author: string, cards: {term: string, definition: string, image: string, sourceImage: string}[]}} The Quizlet data.
*/
getJSON() {
return this.json
}
}