Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import requests
url = input("YouTube URL: ")
filename = "commenters.txt"
#filename = input("Save to: ")
session = requests.Session()
headers = {
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36",
"X-YouTube-Client-Name": "1",
"X-YouTube-Client-Version": "2.20190420"
}
resp = session.get(url, headers=headers)
xsrf_token = resp.text.split("XSRF_TOKEN\":\"")[1].split("\"")[0]
ctoken = resp.text.split("\"nextContinuationData\":{\"continuation\":\"")[1].split("\"")[0]
itct = resp.text.split("\"{}\",\"clickTrackingParams\":\"".format(ctoken))[1].split("\"")[0]
commenters = []
while True:
print("Scrolling. please wait... ({})".format(len(commenters)))
params = {
"action_get_comments": "1",
"pbj": "1",
"ctoken": ctoken,
"continuation": ctoken,
"itct": itct
}
data = {
"session_token": xsrf_token
}
resp = session.post("https://www.youtube.com/comment_service_ajax", params=params, headers=headers, data=data)
jsonResp = resp.json()
doBreak = False
if "continuationContents" in jsonResp["response"] and "continuations" in jsonResp["response"]["continuationContents"]["itemSectionContinuation"]:
ctoken = jsonResp["response"]["continuationContents"]["itemSectionContinuation"]["continuations"][0]["nextContinuationData"]["continuation"]
else:
doBreak = True
if "continuationContents" in jsonResp["response"] and "contents" in jsonResp["response"]["continuationContents"]["itemSectionContinuation"]:
for content in jsonResp["response"]["continuationContents"]["itemSectionContinuation"]["contents"]:
commenters.append(content["commentThreadRenderer"]["comment"]["commentRenderer"]["authorText"]["simpleText"])
if doBreak:
break
commenters = list(set(commenters))
open(filename, "w").write("\n".join(commenters).strip())
print("Warning: YouTube stopped sending a comment info. This means the script has fetch all comments correctly, or YouTube just blocked this script to fetch a comment just now.")
print("Saved {} name(s) (removed duplicates) to {}".format(len(commenters), filename))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment