Importing comments on YouTube or other similar sites

Is there a quick easy way to import all the comments for reading? In particular I want to read YouTube comments and Amazon comments/reviews.

1 Like

Good idea, i’ll add this to the Youtube addon.

To do it manually you can paste this code in the console of your Youtube video.

2 output types: with and without usernames

Just remove the // from the last line in the code to output without usernames

function extractCommentsAndUsernames(includeUsername = true) {
    const commentsArray = []; // Initialize an empty array to hold the comment objects

    // Select all the comment blocks based on the unique structure provided
    const commentBlocks = document.querySelectorAll('div#main.style-scope.ytd-comment-view-model');

    // Iterate over each comment block
    commentBlocks.forEach(commentBlock => {
        let commentObject = {};

        // Extract the username if includeUsername is true
        if (includeUsername) {
            const usernameSelector = commentBlock.querySelector('a#author-text span');
            commentObject.username = usernameSelector ? usernameSelector.textContent.trim() : 'Unknown User';
        }

        // Extract the comment text
        const commentTextSelector = commentBlock.querySelector('yt-attributed-string#content-text');
        commentObject.commentText = commentTextSelector ? commentTextSelector.textContent.trim() : 'No Comment Text Found';

        // Add the extracted information to the comments array
        commentsArray.push(commentObject);
    });

    // Convert comments array to string and trigger download
    downloadCommentsAsText(commentsArray, includeUsername);

    // Return the array of comment objects
    return commentsArray;
}

function downloadCommentsAsText(commentsArray, includeUsername) {
    // Convert the comments array to a string format
    const commentsString = commentsArray.map(comment => includeUsername ? `${comment.username}: ${comment.commentText}` : comment.commentText).join('\n');

    // Create a Blob from the comments string
    const blob = new Blob([commentsString], {type: 'text/plain'});

    // Create a URL for the Blob
    const url = URL.createObjectURL(blob);

    // Create an <a> element with the Blob URL as the href
    const downloadLink = document.createElement('a');
    downloadLink.href = url;
    downloadLink.download = 'comments.txt'; // Name of the file to be downloaded

    // Append the <a> element to the document (this can be hidden)
    document.body.appendChild(downloadLink);

    // Programmatically click the <a> element to trigger the download
    downloadLink.click();

    // Remove the <a> element from the document
    document.body.removeChild(downloadLink);
}

// Example usage:
console.log(extractCommentsAndUsernames(true)); // To include usernames
//console.log(extractCommentsAndUsernames(false)); // To exclude usernames

3 Likes