bing_images.py 2.6KB

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