flickr-noapi.py 2.3 KB

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