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), max. 5000 query/month
  5. #
  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. #
  11. # @todo currently there are up to 35 images receive per page, because bing does not parse count=10. limited response to 10 images
  12. from urllib import urlencode
  13. from cgi import escape
  14. from lxml import html
  15. from yaml import load
  16. import re
  17. # engine dependent config
  18. categories = ['images']
  19. paging = True
  20. # search-url
  21. base_url = 'https://www.bing.com/'
  22. search_string = 'images/search?{query}&count=10&first={offset}'
  23. # do search-request
  24. def request(query, params):
  25. offset = (params['pageno'] - 1) * 10 + 1
  26. # required for cookie
  27. language = 'en-US'
  28. search_path = search_string.format(
  29. query=urlencode({'q': query}),
  30. offset=offset)
  31. params['cookies']['SRCHHPGUSR'] = \
  32. 'NEWWND=0&NRSLT=-1&SRCHLANG=' + language.split('-')[0]
  33. params['url'] = base_url + search_path
  34. print(params['url'])
  35. return params
  36. # get response from search-request
  37. def response(resp):
  38. results = []
  39. dom = html.fromstring(resp.content)
  40. # init regex for yaml-parsing
  41. p = re.compile( '({|,)([a-z]+):(")')
  42. # parse results
  43. for result in dom.xpath('//div[@class="dg_u"]'):
  44. link = result.xpath('./a')[0]
  45. # parse yaml-data (it is required to add a space, to make it parsable)
  46. yaml_data = load(p.sub( r'\1\2: \3', link.attrib.get('m')))
  47. title = link.attrib.get('t1')
  48. #url = 'http://' + link.attrib.get('t3')
  49. url = yaml_data.get('surl')
  50. img_src = yaml_data.get('imgurl')
  51. # append result
  52. results.append({'template': 'images.html',
  53. 'url': url,
  54. 'title': title,
  55. 'content': '',
  56. 'img_src': img_src})
  57. # TODO stop parsing if 10 images are found
  58. if len(results) >= 10:
  59. break
  60. # return results
  61. return results