I wrote a JavaScript script to export YouTube Liked videos data to CSV, so I’ll introduce it briefly.
Function: Export the video list from the liked videos page to CSV in title, URL format and save it.
Issues: URLs can’t be retrieved from videos in the middle. This seems to be a YouTube specification so there’s nothing that can be done. The order is random.
How to use:
Go to the liked videos page, open Chrome Developer Tools, and copy-paste the following source code.
Note: After all, only the last console.save(csv,'result.csv') needs to be executed after waiting a few seconds.
function getElementsByXPath(xpath, parent)
{
let results = [];
let query = document.evaluate(xpath,
parent || document,
null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
for (let i=0, length=query.snapshotLength; i<length; ++i) {
results.push(query.snapshotItem(i));
}
return results;
}
(function(console){
console.save = function(data, filename){
if(!data) {
console.error('Console.save: No data')
return;
}
if(!filename) filename = 'console.json'
if(typeof data === "object"){
data = JSON.stringify(data, undefined, 4)
}
var blob = new Blob([data], {type: 'text/json'}),
e = document.createEvent('MouseEvents'),
a = document.createElement('a')
a.download = filename
a.href = window.URL.createObjectURL(blob)
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
a.dispatchEvent(e)
}
})(console)
var absolutePath = function(href) {
var link = document.createElement("a");
link.href = href;
return link.href;
}
var xpath = '//*[@id="video-title"]' ;
var csv ;
for (i = 1; getElementsByXPath(xpath).length; i++) {
text = getElementsByXPath(xpath)[i].getAttribute("title");
text = text.replace(/,/g, "、");
text = '"' + text + '"'
csv += text
csv += ','
// csv += "\n" ;
text = getElementsByXPath(xpath)[i].getAttribute("href")
text = absolutePath(text) ;
text = text.replace(/,/g, "、");
text = '"' + text + '"'
csv += text
// csv += ','
csv += "\n" ;
}
console.save(csv,'result.csv')
This JavaScript program retrieves elements based on a specific XPath path on a web page, extracts data from those elements, and saves it to a CSV file. Here’s a step-by-step explanation of the program:
-
getElementsByXPathfunction:- A function that takes an XPath expression and parent element and retrieves elements matching the specified XPath.
- Uses
document.evaluateto evaluate the XPath and retrieve matching elements.
-
(function(console){...})(console)section:- Code to extend the
console.savefunction. - The
console.savefunction adds a custom function to save data to a file.
- Code to extend the
-
absolutePathfunction:- A function to convert relative URLs to absolute URLs.
- Converts a given relative URL to an absolute URL using an
<a>element.
-
xpathvariable:- Specifies an XPath expression. This XPath expression is used to extract
<a>elements with anidattribute of “video-title” on the page.
- Specifies an XPath expression. This XPath expression is used to extract
-
csvvariable:- A variable to store CSV data.
-
forloop:- Uses
getElementsByXPath(xpath)to retrieve elements matching the XPath and loops that many times.
- Uses
-
Processing within the loop:
- Uses
getElementsByXPath(xpath)[i].getAttribute("title")to retrieve text data from the element’s “title” attribute. - The retrieved text data is added to the
csvvariable as a CSV cell separated by commas (,). The text data is enclosed in double quotes. - Uses
getElementsByXPath(xpath)[i].getAttribute("href")to retrieve a relative URL from the element’s “href” attribute. - Converts the relative URL to an absolute URL using the
absolutePathfunction, encloses it in double quotes, and adds it to thecsvvariable. - Separates cells with commas and adds a newline character (
\n) at the end of the row.
- Uses
-
console.save(csv, 'result.csv'):- Uses the
console.savefunction to download the contents of thecsvvariable as a CSV file. The filename is ‘result.csv’. This function is custom-defined and serves to save CSV data to a file.
- Uses the
This program retrieves titles and links from elements matching the specified XPath and saves them to a CSV file.
Bonus: Script to click Liked videos (wrote but didn’t use)
for (i=0; i < document.querySelectorAll("#endpoint").length ; i++ ){
// console.log(i) ;
// console.log(document.querySelectorAll("#endpoint")[i].getAttribute('title')) ;
if (document.querySelectorAll("#endpoint")[i].getAttribute('title').match(/Liked videos/) == null){
} else {
// console.log(i) ;
document.querySelectorAll("#endpoint")[i].click()
}
}
This JavaScript code searches for elements on a web page and executes a click action if conditions are met. Specifically, it searches for elements with the ID #endpoint and clicks on elements with the title “Liked videos”. Here’s a step-by-step explanation of the code:
-
forloop:- Initializes the
ivariable to 0 in the loop initialization and executes the loop up todocument.querySelectorAll("#endpoint").length. document.querySelectorAll("#endpoint")is code that retrieves all elements with the#endpointID on the page.
- Initializes the
-
Condition check:
- Uses an
ifstatement to do nothing if the title of the retrieved element is not “Liked videos”. Nothing is done for other elements.
- Uses an
-
Processing when condition matches:
- If an element with the title “Liked videos” is found, executes
document.querySelectorAll("#endpoint")[i].click(). - This clicks on that element.
- If an element with the title “Liked videos” is found, executes
This code is used to click on elements with the title “Liked videos” on the page and does not interfere with other elements. It checks element titles within the loop and triggers a click action if the title matches.