google_scholar.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """Google (Scholar)
  4. For detailed description of the *REST-full* API see: `Query Parameter
  5. Definitions`_.
  6. .. _Query Parameter Definitions:
  7. https://developers.google.com/custom-search/docs/xml_results#WebSearch_Query_Parameter_Definitions
  8. """
  9. # pylint: disable=invalid-name, missing-function-docstring
  10. from urllib.parse import urlencode
  11. from datetime import datetime
  12. from lxml import html
  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. def time_range_url(params):
  46. """Returns a URL query component for a google-Scholar time range based on
  47. ``params['time_range']``. Google-Scholar does only support ranges in years.
  48. To have any effect, all the Searx ranges (*day*, *week*, *month*, *year*)
  49. are mapped to *year*. If no range is set, an empty string is returned.
  50. Example::
  51. &as_ylo=2019
  52. """
  53. # as_ylo=2016&as_yhi=2019
  54. ret_val = ''
  55. if params['time_range'] in time_range_dict:
  56. ret_val= urlencode({'as_ylo': datetime.now().year -1 })
  57. return '&' + ret_val
  58. def request(query, params):
  59. """Google-Scholar search request"""
  60. offset = (params['pageno'] - 1) * 10
  61. lang_info = get_lang_info(
  62. # pylint: disable=undefined-variable
  63. params, supported_languages, language_aliases, False
  64. )
  65. logger.debug(
  66. "HTTP header Accept-Language --> %s", lang_info['headers']['Accept-Language'])
  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. **lang_info['params'],
  72. 'ie': "utf8",
  73. 'oe': "utf8",
  74. 'start' : offset,
  75. })
  76. query_url += time_range_url(params)
  77. params['url'] = query_url
  78. params['headers'].update(lang_info['headers'])
  79. params['headers']['Accept'] = (
  80. 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
  81. )
  82. #params['google_subdomain'] = subdomain
  83. return params
  84. def response(resp):
  85. """Get response from google's search request"""
  86. results = []
  87. detect_google_sorry(resp)
  88. # which subdomain ?
  89. # subdomain = resp.search_params.get('google_subdomain')
  90. # convert the text to dom
  91. dom = html.fromstring(resp.text)
  92. # parse results
  93. for result in eval_xpath_list(dom, '//div[@class="gs_ri"]'):
  94. title = extract_text(eval_xpath(result, './h3[1]//a'))
  95. if not title:
  96. # this is a [ZITATION] block
  97. continue
  98. url = eval_xpath(result, './h3[1]//a/@href')[0]
  99. content = extract_text(eval_xpath(result, './div[@class="gs_rs"]')) or ''
  100. pub_info = extract_text(eval_xpath(result, './div[@class="gs_a"]'))
  101. if pub_info:
  102. content += "[%s]" % pub_info
  103. pub_type = extract_text(eval_xpath(result, './/span[@class="gs_ct1"]'))
  104. if pub_type:
  105. title = title + " " + pub_type
  106. results.append({
  107. 'url': url,
  108. 'title': title,
  109. 'content': content,
  110. })
  111. # parse suggestion
  112. for suggestion in eval_xpath(dom, '//div[contains(@class, "gs_qsuggest_wrap")]//li//a'):
  113. # append suggestion
  114. results.append({'suggestion': extract_text(suggestion)})
  115. for correction in eval_xpath(dom, '//div[@class="gs_r gs_pda"]/a'):
  116. results.append({'correction': extract_text(correction)})
  117. return results