startpage.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. from urllib import urlencode
  2. from lxml import html
  3. from cgi import escape
  4. base_url = None
  5. search_url = None
  6. # TODO paging
  7. paging = False
  8. # TODO complete list of country mapping
  9. country_map = {'en_US': 'eng',
  10. 'en_UK': 'uk',
  11. 'nl_NL': 'ned'}
  12. def request(query, params):
  13. query = urlencode({'q': query})[2:]
  14. params['url'] = search_url
  15. params['method'] = 'POST'
  16. params['data'] = {'query': query,
  17. 'startat': (params['pageno'] - 1) * 10} # offset
  18. country = country_map.get(params['language'], 'eng')
  19. params['cookies']['preferences'] = \
  20. 'lang_homepageEEEs/air/{country}/N1NsslEEE1N1Nfont_sizeEEEmediumN1Nrecent_results_filterEEE1N1Nlanguage_uiEEEenglishN1Ndisable_open_in_new_windowEEE0N1Ncolor_schemeEEEnewN1Nnum_of_resultsEEE10N1N'.format(country=country) # noqa
  21. return params
  22. def response(resp):
  23. results = []
  24. dom = html.fromstring(resp.content)
  25. # ads xpath //div[@id="results"]/div[@id="sponsored"]//div[@class="result"]
  26. # not ads: div[@class="result"] are the direct childs of div[@id="results"]
  27. for result in dom.xpath('//div[@class="result"]'):
  28. link = result.xpath('.//h3/a')[0]
  29. url = link.attrib.get('href')
  30. if url.startswith('http://www.google.')\
  31. or url.startswith('https://www.google.'):
  32. continue
  33. title = escape(link.text_content())
  34. content = ''
  35. if result.xpath('./p[@class="desc"]'):
  36. content = escape(result.xpath('./p[@class="desc"]')[0].text_content())
  37. results.append({'url': url, 'title': title, 'content': content})
  38. return results