mediawiki.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. """
  2. general mediawiki-engine (Web)
  3. @website websites built on mediawiki (https://www.mediawiki.org)
  4. @provide-api yes (http://www.mediawiki.org/wiki/API:Search)
  5. @using-api yes
  6. @results JSON
  7. @stable yes
  8. @parse url, title
  9. @todo content
  10. """
  11. from json import loads
  12. from string import Formatter
  13. from urllib import urlencode, quote
  14. # engine dependent config
  15. categories = ['general']
  16. language_support = True
  17. paging = True
  18. number_of_results = 1
  19. # search-url
  20. base_url = 'https://{language}.wikipedia.org/'
  21. search_url = base_url + 'w/api.php?action=query'\
  22. '&list=search'\
  23. '&{query}'\
  24. '&srprop=timestamp'\
  25. '&format=json'\
  26. '&sroffset={offset}'\
  27. '&srlimit={limit}' # noqa
  28. # do search-request
  29. def request(query, params):
  30. offset = (params['pageno'] - 1) * number_of_results
  31. string_args = dict(query=urlencode({'srsearch': query}),
  32. offset=offset,
  33. limit=number_of_results)
  34. format_strings = list(Formatter().parse(base_url))
  35. if params['language'] == 'all':
  36. language = 'en'
  37. else:
  38. language = params['language'].split('_')[0]
  39. if len(format_strings) > 1:
  40. string_args['language'] = language
  41. # write search-language back to params, required in response
  42. params['language'] = language
  43. params['url'] = search_url.format(**string_args)
  44. return params
  45. # get response from search-request
  46. def response(resp):
  47. results = []
  48. search_results = loads(resp.text)
  49. # return empty array if there are no results
  50. if not search_results.get('query', {}).get('search'):
  51. return []
  52. # parse results
  53. for result in search_results['query']['search']:
  54. url = base_url.format(language=resp.search_params['language']) +\
  55. 'wiki/' + quote(result['title'].replace(' ', '_').encode('utf-8'))
  56. # append result
  57. results.append({'url': url,
  58. 'title': result['title'],
  59. 'content': ''})
  60. # return results
  61. return results