flickr_noapi.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. #!/usr/bin/env python
  2. """
  3. Flickr (Images)
  4. @website https://www.flickr.com
  5. @provide-api yes (https://secure.flickr.com/services/api/flickr.photos.search.html)
  6. @using-api no
  7. @results HTML
  8. @stable no
  9. @parse url, title, thumbnail, img_src
  10. """
  11. from urllib import urlencode
  12. from json import loads
  13. import re
  14. from searx.engines import logger
  15. logger = logger.getChild('flickr-noapi')
  16. categories = ['images']
  17. url = 'https://www.flickr.com/'
  18. search_url = url + 'search?{query}&page={page}'
  19. photo_url = 'https://www.flickr.com/photos/{userid}/{photoid}'
  20. regex = re.compile(r"\"search-photos-lite-models\",\"photos\":(.*}),\"totalItems\":", re.DOTALL)
  21. image_sizes = ('o', 'k', 'h', 'b', 'c', 'z', 'n', 'm', 't', 'q', 's')
  22. paging = True
  23. def build_flickr_url(user_id, photo_id):
  24. return photo_url.format(userid=user_id, photoid=photo_id)
  25. def request(query, params):
  26. params['url'] = search_url.format(query=urlencode({'text': query}),
  27. page=params['pageno'])
  28. return params
  29. def response(resp):
  30. results = []
  31. matches = regex.search(resp.text)
  32. if matches is None:
  33. return results
  34. match = matches.group(1)
  35. search_results = loads(match)
  36. if '_data' not in search_results:
  37. return []
  38. photos = search_results['_data']
  39. for photo in photos:
  40. # In paged configuration, the first pages' photos
  41. # are represented by a None object
  42. if photo is None:
  43. continue
  44. img_src = None
  45. # From the biggest to the lowest format
  46. for image_size in image_sizes:
  47. if image_size in photo['sizes']:
  48. img_src = photo['sizes'][image_size]['url']
  49. break
  50. if not img_src:
  51. logger.debug('cannot find valid image size: {0}'.format(repr(photo)))
  52. continue
  53. if 'ownerNsid' not in photo:
  54. continue
  55. # For a bigger thumbnail, keep only the url_z, not the url_n
  56. if 'n' in photo['sizes']:
  57. thumbnail_src = photo['sizes']['n']['url']
  58. elif 'z' in photo['sizes']:
  59. thumbnail_src = photo['sizes']['z']['url']
  60. else:
  61. thumbnail_src = img_src
  62. url = build_flickr_url(photo['ownerNsid'], photo['id'])
  63. title = photo.get('title', '')
  64. content = '<span class="photo-author">' +\
  65. photo['username'] +\
  66. '</span><br />'
  67. # append result
  68. results.append({'url': url,
  69. 'title': title,
  70. 'img_src': img_src,
  71. 'thumbnail_src': thumbnail_src,
  72. 'content': content,
  73. 'template': 'images.html'})
  74. return results