summaryrefslogtreecommitdiffstats
path: root/YouTubeStats.py
blob: f454ebd1a37992d432fdab6a82bf89b2065cc5d4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# -*- coding: iso-8859-1 -*-
#!/usr/bin/env python

from urllib2 import urlopen
from json import loads
from urllib import quote_plus
from re import findall

def searchVolume(keyword):
	response = loads(urlopen("https://ads.youtube.com/keyword_tool_ajax?action_get_kw_count=1&query=%s&country=US" % quote_plus(keyword)).read())
	ret = {
		'broad': 0,
		'exact': 0
		}
	if response["error"] != None or len(response["count"]) == 0:
		return ret
	ret['broad'] = int(response["count"][0]["broad"])
	ret['exact'] = int(response["count"][0]["exact"])
	return ret
		
def viewCount(keyword):
	viewCounts = 0
	for page in range(1, 51):
		html = urlopen("http://www.youtube.com/results?search_query=%s&page=%s" % (quote_plus(keyword), page)).read()
		if html.find("No videos found for") != -1:
			return 0
		html = html[html.index("<!-- start search results -->") : html.index("<!-- end search results -->")]
		viewCountScrape = findall('class="video-view-count"[ ]{0,1}>([0-9,]+) views\s{0,1}</span>', html)
		if len(viewCountScrape) == 0:
			break
		for viewCount in viewCountScrape:
			viewCounts += int(viewCount.replace(",", ""))
	return viewCounts