Download your Coursera lectures using JS, bash and wget

So, in light of recent events, I was unable to follow up on my Coursera Algorithms course.

Trying to find a way to download all the lectures at once, I couldn’t find a way that worked for me – I found two, but they simply didn’t work. With the help of some JavaScript that I got from one of these sources, I cooked up the following steps to easily download all the lectures at once:

Step 1: Extract the lecture names, and their IDs from the Coursera page
Navigate to your lecture page(for me, it was https://class.coursera.org/algs4partII-003/lecture).
Execute the following JavaScript in the Console(in Chrome, use the Inspect Element option):

function findLectures () {
  var link_elems = document.querySelectorAll('.lecture-link');
  var lectures = "";
  Array.prototype.slice.call(link_elems).forEach(function (elem, i) {
    var lecture = i + "|" + elem.getAttribute('data-lecture-id') + "|" + elem.innerText.trim();
    lectures += lecture + "\n";
  });
  return lectures;
}

Then call the method findLectures(). This will print each lecture in the following format: Lecture position in page|Lecture ID|Lecture name.
Example output:

0|43|Course Introduction (9:22)
1|1|Introduction to Graphs (9:32)
2|2|Graph API (14:47)

Save this to a file named lectures.txt(exclude any quotes that get pasted)

Step 2: Export Coursera’s cookies
Use the Chrome plugin cookie.txt export to export all the cookies that Coursera has saved. Save the result to a file named cookies.txt

Step 3: Download them!
Run the following in the terminal:

export COUNT=1; while read line; do lecture_name=`echo $line | awk -F '|' {'print $3'}` lecture_id=`echo $line | awk -F '|' {'print $2'}`; echo "Downloading lecture $COUNT; ID=$lecture_id; Name=$lecture_name..."; ((COUNT++)); wget --load-cookies cookies.txt https://class.coursera.org/algs4partII-003/lecture/download.mp4?lecture_id=$lecture_id -O "$COUNT - $lecture_name"; done < lectures.txt

Make sure you replace the link to where your lectures are listed. The above link has “https://class.coursera.org/algs4partII-003/lecture/” in it.

This will download all the lectures in the current working directory. It does not maintain any relationship with the week that the lecture was released in. It downloads them in the order that they are listed on the Coursera lecture page.