Python to Scraping a Youtube Comment From URL with Full Source Code For Beginners

This script will take a URL of a youtube video and it will give CSV file for users and comments.

Prerequisites:

  • You only need to have installed selenium which is used for automation.
  • Run the below script to install selenium
$ pip install selenium

Run the Script:

  • Simply replace your own youtube video url in the webscrapindcomment.py
  • And run command in the same directory
  • python webscrapindcomment.py

Source Code:

webscrapindcomment.py

from selenium import webdriver import csv import time items=[] driver=webdriver.Chrome(r"C:/Users/hp/Anaconda3/chromedriver.exe") driver.get('https://www.youtube.com/watch?v=iFPMz36std4') driver.execute_script('window.scrollTo(1, 500);') #now wait let load the comments time.sleep(5) driver.execute_script('window.scrollTo(1, 3000);') username_elems = driver.find_elements_by_xpath('//*[@id="author-text"]') comment_elems = driver.find_elements_by_xpath('//*[@id="content-text"]') for username, comment in zip(username_elems, comment_elems): item = {} item['Author'] = username.text item['Comment'] = comment.text items.append(item) filename = 'C:/Users/hp/Desktop/commentlist.csv' with open(filename, 'w', newline='', encoding='utf-8') as f: w = csv.DictWriter(f,['Author','Comment']) w.writeheader() for item in items: w.writerow(item)
Code language: PHP (php)

Leave a Comment