bing_images.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. # do search-request
  26. def request(query, params):
  27. offset = (params['pageno'] - 1) * 10 + 1
  28. # required for cookie
  29. language = 'en-US'
  30. search_path = search_string.format(
  31. query=urlencode({'q': query}),
  32. offset=offset)
  33. params['cookies']['SRCHHPGUSR'] = \
  34. 'NEWWND=0&NRSLT=-1&SRCHLANG=' + language.split('-')[0]
  35. params['url'] = base_url + search_path
  36. return params
  37. # get response from search-request
  38. def response(resp):
  39. results = []
  40. dom = html.fromstring(resp.content)
  41. # init regex for yaml-parsing
  42. p = re.compile('({|,)([a-z]+):(")')
  43. # parse results
  44. for result in dom.xpath('//div[@class="dg_u"]'):
  45. link = result.xpath('./a')[0]
  46. # parse yaml-data (it is required to add a space, to make it parsable)
  47. yaml_data = load(p.sub(r'\1\2: \3', link.attrib.get('m')))
  48. title = link.attrib.get('t1')
  49. #url = 'http://' + link.attrib.get('t3')
  50. url = yaml_data.get('surl')
  51. img_src = yaml_data.get('imgurl')
  52. # append result
  53. results.append({'template': 'images.html',
  54. 'url': url,
  55. 'title': title,
  56. 'content': '',
  57. 'img_src': img_src})
  58. # TODO stop parsing if 10 images are found
  59. if len(results) >= 10:
  60. break
  61. # return results
  62. return results