bing_videos.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. """
  2. Bing (Videos)
  3. @website https://www.bing.com/videos
  4. @provide-api yes (http://datamarket.azure.com/dataset/bing/search)
  5. @using-api no
  6. @results HTML
  7. @stable no
  8. @parse url, title, content, thumbnail
  9. """
  10. from json import loads
  11. from lxml import html
  12. from searx.engines.xpath import extract_text
  13. from searx.url_utils import urlencode
  14. categories = ['videos']
  15. paging = True
  16. safesearch = True
  17. time_range_support = True
  18. number_of_results = 10
  19. search_url = 'https://www.bing.com/videos/asyncv2?{query}&async=content&'\
  20. 'first={offset}&count={number_of_results}&CW=1366&CH=25&FORM=R5VR5'
  21. time_range_string = '&qft=+filterui:videoage-lt{interval}'
  22. time_range_dict = {'day': '1440',
  23. 'week': '10080',
  24. 'month': '43200',
  25. 'year': '525600'}
  26. # safesearch definitions
  27. safesearch_types = {2: 'STRICT',
  28. 1: 'DEMOTE',
  29. 0: 'OFF'}
  30. # do search-request
  31. def request(query, params):
  32. offset = (params['pageno'] - 1) * 10 + 1
  33. # safesearch cookie
  34. params['cookies']['SRCHHPGUSR'] = \
  35. 'ADLT=' + safesearch_types.get(params['safesearch'], 'DEMOTE')
  36. # language cookie
  37. params['cookies']['_EDGE_S'] = 'mkt=' + params['language'].lower() + '&F=1'
  38. # query and paging
  39. params['url'] = search_url.format(query=urlencode({'q': query}),
  40. offset=offset,
  41. number_of_results=number_of_results)
  42. # time range
  43. if params['time_range'] in time_range_dict:
  44. params['url'] += time_range_string.format(interval=time_range_dict[params['time_range']])
  45. return params
  46. # get response from search-request
  47. def response(resp):
  48. results = []
  49. dom = html.fromstring(resp.text)
  50. for result in dom.xpath('//div[@class="dg_u"]'):
  51. # try to extract the url
  52. url_container = result.xpath('.//div[@class="sa_wrapper"]/@data-eventpayload')
  53. if len(url_container) > 0:
  54. url = loads(url_container[0])['purl']
  55. else:
  56. url = result.xpath('./a/@href')[0]
  57. # discard results that do not return an external url
  58. # very recent results sometimes don't return the video's url
  59. if url.startswith('/videos/search?'):
  60. continue
  61. title = extract_text(result.xpath('./a//div[@class="tl"]'))
  62. content = extract_text(result.xpath('.//div[@class="pubInfo"]'))
  63. thumbnail = result.xpath('.//div[@class="vthumb"]/img/@src')[0]
  64. results.append({'url': url,
  65. 'title': title,
  66. 'content': content,
  67. 'thumbnail': thumbnail,
  68. 'template': 'videos.html'})
  69. # first page ignores requested number of results
  70. if len(results) >= number_of_results:
  71. break
  72. return results