bing_images.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. ## Bing (Images)
  2. #
  3. # @website https://www.bing.com/images
  4. # @provide-api yes (http://datamarket.azure.com/dataset/bing/search),
  5. # max. 5000 query/month
  6. #
  7. # @using-api no (because of query limit)
  8. # @results HTML (using search portal)
  9. # @stable no (HTML can change)
  10. # @parse url, title, img_src
  11. #
  12. # @todo currently there are up to 35 images receive per page,
  13. # because bing does not parse count=10.
  14. # limited response to 10 images
  15. from urllib import urlencode
  16. from lxml import html
  17. from yaml import load
  18. import re
  19. # engine dependent config
  20. categories = ['images']
  21. paging = True
  22. # search-url
  23. base_url = 'https://www.bing.com/'
  24. search_string = 'images/search?{query}&count=10&first={offset}'
  25. thumb_url = "http://ts1.mm.bing.net/th?id={ihk}"
  26. # do search-request
  27. def request(query, params):
  28. offset = (params['pageno'] - 1) * 10 + 1
  29. # required for cookie
  30. if params['language'] == 'all':
  31. language = 'en-US'
  32. else:
  33. language = params['language'].replace('_', '-')
  34. search_path = search_string.format(
  35. query=urlencode({'q': query}),
  36. offset=offset)
  37. params['cookies']['SRCHHPGUSR'] = \
  38. 'NEWWND=0&NRSLT=-1&SRCHLANG=' + language.split('-')[0]
  39. params['url'] = base_url + search_path
  40. return params
  41. # get response from search-request
  42. def response(resp):
  43. results = []
  44. dom = html.fromstring(resp.content)
  45. # init regex for yaml-parsing
  46. p = re.compile('({|,)([a-z]+):(")')
  47. # parse results
  48. for result in dom.xpath('//div[@class="dg_u"]'):
  49. link = result.xpath('./a')[0]
  50. # parse yaml-data (it is required to add a space, to make it parsable)
  51. yaml_data = load(p.sub(r'\1\2: \3', link.attrib.get('m')))
  52. title = link.attrib.get('t1')
  53. ihk = link.attrib.get('ihk')
  54. #url = 'http://' + link.attrib.get('t3')
  55. url = yaml_data.get('surl')
  56. img_src = yaml_data.get('imgurl')
  57. # append result
  58. results.append({'template': 'images.html',
  59. 'url': url,
  60. 'title': title,
  61. 'content': '',
  62. 'thumbnail_src': thumb_url.format(ihk=ihk),
  63. 'img_src': img_src})
  64. # TODO stop parsing if 10 images are found
  65. if len(results) >= 10:
  66. break
  67. # return results
  68. return results