youtube_noapi.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. # Youtube (Videos)
  2. #
  3. # @website https://www.youtube.com/
  4. # @provide-api yes (https://developers.google.com/apis-explorer/#p/youtube/v3/youtube.search.list)
  5. #
  6. # @using-api no
  7. # @results HTML
  8. # @stable no
  9. # @parse url, title, content, publishedDate, thumbnail, embedded
  10. from urllib import quote_plus
  11. from lxml import html
  12. from searx.engines.xpath import extract_text
  13. from searx.utils import list_get
  14. # engine dependent config
  15. categories = ['videos', 'music']
  16. paging = True
  17. language_support = False
  18. # search-url
  19. base_url = 'https://www.youtube.com/results'
  20. search_url = base_url + '?search_query={query}&page={page}'
  21. embedded_url = '<iframe width="540" height="304" ' +\
  22. 'data-src="//www.youtube-nocookie.com/embed/{videoid}" ' +\
  23. 'frameborder="0" allowfullscreen></iframe>'
  24. base_youtube_url = 'https://www.youtube.com/watch?v='
  25. # specific xpath variables
  26. results_xpath = "//ol/li/div[contains(@class, 'yt-lockup yt-lockup-tile yt-lockup-video vve-check')]"
  27. url_xpath = './/h3/a/@href'
  28. title_xpath = './/div[@class="yt-lockup-content"]/h3/a'
  29. content_xpath = './/div[@class="yt-lockup-content"]/div[@class="yt-lockup-description yt-ui-ellipsis yt-ui-ellipsis-2"]'
  30. # returns extract_text on the first result selected by the xpath or None
  31. def extract_text_from_dom(result, xpath):
  32. r = result.xpath(xpath)
  33. if len(r) > 0:
  34. return extract_text(r[0])
  35. return None
  36. # do search-request
  37. def request(query, params):
  38. params['url'] = search_url.format(query=quote_plus(query),
  39. page=params['pageno'])
  40. return params
  41. # get response from search-request
  42. def response(resp):
  43. results = []
  44. dom = html.fromstring(resp.text)
  45. # parse results
  46. for result in dom.xpath(results_xpath):
  47. videoid = list_get(result.xpath('@data-context-item-id'), 0)
  48. if videoid is not None:
  49. url = base_youtube_url + videoid
  50. thumbnail = 'https://i.ytimg.com/vi/' + videoid + '/hqdefault.jpg'
  51. title = extract_text_from_dom(result, title_xpath) or videoid
  52. content = extract_text_from_dom(result, content_xpath)
  53. embedded = embedded_url.format(videoid=videoid)
  54. # append result
  55. results.append({'url': url,
  56. 'title': title,
  57. 'content': content,
  58. 'template': 'videos.html',
  59. 'embedded': embedded,
  60. 'thumbnail': thumbnail})
  61. # return results
  62. return results