Skip to content

Instantly share code, notes, and snippets.

@jeffreymeng
Last active June 3, 2023 21:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffreymeng/921a1e949e59ed1d843702440175b0a1 to your computer and use it in GitHub Desktop.
Save jeffreymeng/921a1e949e59ed1d843702440175b0a1 to your computer and use it in GitHub Desktop.
Canvas Quiz Scraper

This script can scrape the quiz result view of canvas, capturing questions, answers, and images. It automatically downloads a JSON file with the scraped data, and downloads each image individually. The scraped data will track your selected answers (independent of whether they are correct). This script is designed to be run in the chrome dev console. You will need to first load jquery if it is not in scope, which can be accomplished by going to the jquery website and copy-pasting the jquery.min.js file into the console.

Due to the nature of web scraping, you may need to adapt this code to fit the specific page semantics you're working with.

((quiz) => {
function downloadURL(url, filename) {
fetch(url)
.then(response => response.blob())
.then(blob => {
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = filename;
link.click();
})
}
function downloadJSON(obj, filename) {
const link = document.createElement("a");
link.href = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(obj, null, 4));
link.download = filename;
link.click();
}
const questions = $(".question").map((i, q) => ({
question: $(q).find("div.question_text").html().trim(),
image: $(q).find(".question_text img").attr("src") || null,
answers: $(q).find(".select_answer.answer_type").map((j, a) => ({
correct: $(a).find(".question_input").is(':checked'),
content: $(a).find(".answer_text").text() || $(a).find(".answer_html").html()
})).get()
})).get();
questions.map((x, i) => {
if(x.image) {
downloadURL(x.image, `quiz_${quiz}_question_${i + 1}.png`);
x.image = `quiz_${quiz}_question_${i + 1}.png`
}
return x;
});
downloadJSON(questions, `quiz_${quiz}.json`);
return questions;
})(replace_me); // <== replace this with some identifier for your quiz, like a number or name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment