google_scholar.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Google (Scholar)
  3. For detailed description of the *REST-full* API see: `Query Parameter
  4. Definitions`_.
  5. .. _Query Parameter Definitions:
  6. https://developers.google.com/custom-search/docs/xml_results#WebSearch_Query_Parameter_Definitions
  7. """
  8. # pylint: disable=invalid-name, missing-function-docstring
  9. from urllib.parse import urlencode
  10. from datetime import datetime
  11. from lxml import html
  12. from searx import logger
  13. from searx.utils import (
  14. eval_xpath,
  15. eval_xpath_list,
  16. extract_text,
  17. )
  18. from searx.engines.google import (
  19. get_lang_info,
  20. time_range_dict,
  21. detect_google_sorry,
  22. )
  23. # pylint: disable=unused-import
  24. from searx.engines.google import (
  25. supported_languages_url,
  26. _fetch_supported_languages,
  27. )
  28. # pylint: enable=unused-import
  29. # about
  30. about = {
  31. "website": 'https://scholar.google.com',
  32. "wikidata_id": 'Q494817',
  33. "official_api_documentation": 'https://developers.google.com/custom-search',
  34. "use_official_api": False,
  35. "require_api_key": False,
  36. "results": 'HTML',
  37. }
  38. # engine dependent config
  39. categories = ['science']
  40. paging = True
  41. language_support = True
  42. use_locale_domain = True
  43. time_range_support = True
  44. safesearch = False
  45. logger = logger.getChild('google scholar')
  46. def time_range_url(params):
  47. """Returns a URL query component for a google-Scholar time range based on
  48. ``params['time_range']``. Google-Scholar does only support ranges in years.
  49. To have any effect, all the Searx ranges (*day*, *week*, *month*, *year*)
  50. are mapped to *year*. If no range is set, an empty string is returned.
  51. Example::
  52. &as_ylo=2019
  53. """
  54. # as_ylo=2016&as_yhi=2019
  55. ret_val = ''
  56. if params['time_range'] in time_range_dict:
  57. ret_val= urlencode({'as_ylo': datetime.now().year -1 })
  58. return '&' + ret_val
  59. def request(query, params):
  60. """Google-Scholar search request"""
  61. offset = (params['pageno'] - 1) * 10
  62. lang_info = get_lang_info(
  63. # pylint: disable=undefined-variable
  64. # params, {}, language_aliases
  65. params, supported_languages, language_aliases
  66. )
  67. # subdomain is: scholar.google.xy
  68. lang_info['subdomain'] = lang_info['subdomain'].replace("www.", "scholar.")
  69. query_url = 'https://'+ lang_info['subdomain'] + '/scholar' + "?" + urlencode({
  70. 'q': query,
  71. 'hl': lang_info['hl'],
  72. 'lr': lang_info['lr'],
  73. 'ie': "utf8",
  74. 'oe': "utf8",
  75. 'start' : offset,
  76. })
  77. query_url += time_range_url(params)
  78. logger.debug("query_url --> %s", query_url)
  79. params['url'] = query_url
  80. logger.debug("HTTP header Accept-Language --> %s", lang_info['Accept-Language'])
  81. params['headers']['Accept-Language'] = lang_info['Accept-Language']
  82. params['headers']['Accept'] = (
  83. 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
  84. )
  85. #params['google_subdomain'] = subdomain
  86. return params
  87. def response(resp):
  88. """Get response from google's search request"""
  89. results = []
  90. detect_google_sorry(resp)
  91. # which subdomain ?
  92. # subdomain = resp.search_params.get('google_subdomain')
  93. # convert the text to dom
  94. dom = html.fromstring(resp.text)
  95. # parse results
  96. for result in eval_xpath_list(dom, '//div[@class="gs_ri"]'):
  97. title = extract_text(eval_xpath(result, './h3[1]//a'))
  98. if not title:
  99. # this is a [ZITATION] block
  100. continue
  101. url = eval_xpath(result, './h3[1]//a/@href')[0]
  102. content = extract_text(eval_xpath(result, './div[@class="gs_rs"]')) or ''
  103. pub_info = extract_text(eval_xpath(result, './div[@class="gs_a"]'))
  104. if pub_info:
  105. content += "[%s]" % pub_info
  106. pub_type = extract_text(eval_xpath(result, './/span[@class="gs_ct1"]'))
  107. if pub_type:
  108. title = title + " " + pub_type
  109. results.append({
  110. 'url': url,
  111. 'title': title,
  112. 'content': content,
  113. })
  114. # parse suggestion
  115. for suggestion in eval_xpath(dom, '//div[contains(@class, "gs_qsuggest_wrap")]//li//a'):
  116. # append suggestion
  117. results.append({'suggestion': extract_text(suggestion)})
  118. for correction in eval_xpath(dom, '//div[@class="gs_r gs_pda"]/a'):
  119. results.append({'correction': extract_text(correction)})
  120. return results