searxng/searx/engines/youtube.py

89 lines
2.4 KiB
Python
Raw Normal View History

## Youtube (Videos)
#
# @website https://www.youtube.com/
# @provide-api yes (http://gdata-samples-youtube-search-py.appspot.com/)
#
# @using-api yes
# @results JSON
# @stable yes
# @parse url, title, content, publishedDate, thumbnail
2013-10-19 18:46:10 +00:00
from json import loads
2013-10-23 21:55:37 +00:00
from urllib import urlencode
2014-03-18 12:19:50 +00:00
from dateutil import parser
2013-10-19 18:46:10 +00:00
# engine dependent config
2013-10-19 18:46:10 +00:00
categories = ['videos']
2014-01-29 23:50:47 +00:00
paging = True
language_support = True
# search-url
base_url = 'https://gdata.youtube.com/feeds/api/videos'
search_url = base_url + '?alt=json&{query}&start-index={index}&max-results=5' # noqa
2013-10-19 18:46:10 +00:00
2014-01-20 01:31:20 +00:00
# do search-request
2013-10-19 18:46:10 +00:00
def request(query, params):
index = (params['pageno'] - 1) * 5 + 1
2014-01-29 23:50:47 +00:00
params['url'] = search_url.format(query=urlencode({'q': query}),
index=index)
# add language tag if specified
if params['language'] != 'all':
params['url'] += '&lr=' + params['language'].split('_')[0]
2013-10-19 18:46:10 +00:00
return params
# get response from search-request
2013-10-19 18:46:10 +00:00
def response(resp):
results = []
2013-10-19 18:46:10 +00:00
search_results = loads(resp.text)
# return empty array if there are no results
2013-10-19 18:46:10 +00:00
if not 'feed' in search_results:
return []
2013-10-19 18:46:10 +00:00
feed = search_results['feed']
2014-02-11 12:13:51 +00:00
# parse results
2013-10-19 18:46:10 +00:00
for result in feed['entry']:
url = [x['href'] for x in result['link'] if x['type'] == 'text/html']
2014-02-11 12:13:51 +00:00
if not url:
2013-10-19 18:46:10 +00:00
return
2013-10-19 18:46:10 +00:00
# remove tracking
url = url[0].replace('feature=youtube_gdata', '')
if url.endswith('&'):
url = url[:-1]
2013-10-19 18:46:10 +00:00
title = result['title']['$t']
content = ''
thumbnail = ''
2014-02-11 12:13:51 +00:00
2014-03-18 12:19:50 +00:00
pubdate = result['published']['$t']
publishedDate = parser.parse(pubdate)
2014-02-11 12:13:51 +00:00
if result['media$group']['media$thumbnail']:
thumbnail = result['media$group']['media$thumbnail'][0]['url']
2014-01-20 01:31:20 +00:00
content += '<a href="{0}" title="{0}" ><img src="{1}" /></a>'.format(url, thumbnail) # noqa
2014-02-11 12:13:51 +00:00
if content:
content += '<br />' + result['content']['$t']
else:
content = result['content']['$t']
# append result
2014-01-20 01:31:20 +00:00
results.append({'url': url,
'title': title,
'content': content,
'template': 'videos.html',
2014-03-18 12:19:50 +00:00
'publishedDate': publishedDate,
2014-01-20 01:31:20 +00:00
'thumbnail': thumbnail})
2013-10-19 18:46:10 +00:00
# return results
2013-10-19 18:46:10 +00:00
return results