google_scholar.py 4.4 KB

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