.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
google_scholar.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2"""This is the implementation of the Google Scholar engine.
3
4Compared to other Google services the Scholar engine has a simple GET REST-API
5and there does not exists `async` API. Even though the API slightly vintage we
6can make use of the :ref:`google API` to assemble the arguments of the GET
7request.
8"""
9
10from typing import TYPE_CHECKING
11from typing import Optional
12
13from urllib.parse import urlencode
14from datetime import datetime
15from lxml import html
16
17from searx.utils import (
18 eval_xpath,
19 eval_xpath_getindex,
20 eval_xpath_list,
21 extract_text,
22)
23
24from searx.exceptions import SearxEngineCaptchaException
25
26from searx.engines.google import fetch_traits # pylint: disable=unused-import
27from searx.engines.google import (
28 get_google_info,
29 time_range_dict,
30)
31from searx.enginelib.traits import EngineTraits
32
33if TYPE_CHECKING:
34 import logging
35
36 logger: logging.Logger
37
38traits: EngineTraits
39
40# about
41about = {
42 "website": 'https://scholar.google.com',
43 "wikidata_id": 'Q494817',
44 "official_api_documentation": 'https://developers.google.com/custom-search',
45 "use_official_api": False,
46 "require_api_key": False,
47 "results": 'HTML',
48}
49
50# engine dependent config
51categories = ['science', 'scientific publications']
52paging = True
53max_page = 50
54language_support = True
55time_range_support = True
56safesearch = False
57send_accept_language_header = True
58
59
60def time_range_args(params):
61 """Returns a dictionary with a time range arguments based on
62 ``params['time_range']``.
63
64 Google Scholar supports a detailed search by year. Searching by *last
65 month* or *last week* (as offered by SearXNG) is uncommon for scientific
66 publications and is not supported by Google Scholar.
67
68 To limit the result list when the users selects a range, all the SearXNG
69 ranges (*day*, *week*, *month*, *year*) are mapped to *year*. If no range
70 is set an empty dictionary of arguments is returned. Example; when
71 user selects a time range (current year minus one in 2022):
72
73 .. code:: python
74
75 { 'as_ylo' : 2021 }
76
77 """
78 ret_val = {}
79 if params['time_range'] in time_range_dict:
80 ret_val['as_ylo'] = datetime.now().year - 1
81 return ret_val
82
83
85 """In case of CAPTCHA Google Scholar open its own *not a Robot* dialog and is
86 not redirected to ``sorry.google.com``.
87 """
88 if eval_xpath(dom, "//form[@id='gs_captcha_f']"):
90
91
92def request(query, params):
93 """Google-Scholar search request"""
94
95 google_info = get_google_info(params, traits)
96 # subdomain is: scholar.google.xy
97 google_info['subdomain'] = google_info['subdomain'].replace("www.", "scholar.")
98
99 args = {
100 'q': query,
101 **google_info['params'],
102 'start': (params['pageno'] - 1) * 10,
103 'as_sdt': '2007', # include patents / to disable set '0,5'
104 'as_vis': '0', # include citations / to disable set '1'
105 }
106 args.update(time_range_args(params))
107
108 params['url'] = 'https://' + google_info['subdomain'] + '/scholar?' + urlencode(args)
109 params['cookies'] = google_info['cookies']
110 params['headers'].update(google_info['headers'])
111 return params
112
113
114def parse_gs_a(text: Optional[str]):
115 """Parse the text written in green.
116
117 Possible formats:
118 * "{authors} - {journal}, {year} - {publisher}"
119 * "{authors} - {year} - {publisher}"
120 * "{authors} - {publisher}"
121 """
122 if text is None or text == "":
123 return None, None, None, None
124
125 s_text = text.split(' - ')
126 authors = s_text[0].split(', ')
127 publisher = s_text[-1]
128 if len(s_text) != 3:
129 return authors, None, publisher, None
130
131 # the format is "{authors} - {journal}, {year} - {publisher}" or "{authors} - {year} - {publisher}"
132 # get journal and year
133 journal_year = s_text[1].split(', ')
134 # journal is optional and may contains some coma
135 if len(journal_year) > 1:
136 journal = ', '.join(journal_year[0:-1])
137 if journal == '…':
138 journal = None
139 else:
140 journal = None
141 # year
142 year = journal_year[-1]
143 try:
144 publishedDate = datetime.strptime(year.strip(), '%Y')
145 except ValueError:
146 publishedDate = None
147 return authors, journal, publisher, publishedDate
148
149
150def response(resp): # pylint: disable=too-many-locals
151 """Parse response from Google Scholar"""
152 results = []
153
154 # convert the text to dom
155 dom = html.fromstring(resp.text)
156 detect_google_captcha(dom)
157
158 # parse results
159 for result in eval_xpath_list(dom, '//div[@data-rp]'):
160
161 title = extract_text(eval_xpath(result, './/h3[1]//a'))
162
163 if not title:
164 # this is a [ZITATION] block
165 continue
166
167 pub_type = extract_text(eval_xpath(result, './/span[@class="gs_ctg2"]'))
168 if pub_type:
169 pub_type = pub_type[1:-1].lower()
170
171 url = eval_xpath_getindex(result, './/h3[1]//a/@href', 0)
172 content = extract_text(eval_xpath(result, './/div[@class="gs_rs"]'))
173 authors, journal, publisher, publishedDate = parse_gs_a(
174 extract_text(eval_xpath(result, './/div[@class="gs_a"]'))
175 )
176 if publisher in url:
177 publisher = None
178
179 # cited by
180 comments = extract_text(eval_xpath(result, './/div[@class="gs_fl"]/a[starts-with(@href,"/scholar?cites=")]'))
181
182 # link to the html or pdf document
183 html_url = None
184 pdf_url = None
185 doc_url = eval_xpath_getindex(result, './/div[@class="gs_or_ggsm"]/a/@href', 0, default=None)
186 doc_type = extract_text(eval_xpath(result, './/span[@class="gs_ctg2"]'))
187 if doc_type == "[PDF]":
188 pdf_url = doc_url
189 else:
190 html_url = doc_url
191
192 results.append(
193 {
194 'template': 'paper.html',
195 'type': pub_type,
196 'url': url,
197 'title': title,
198 'authors': authors,
199 'publisher': publisher,
200 'journal': journal,
201 'publishedDate': publishedDate,
202 'content': content,
203 'comments': comments,
204 'html_url': html_url,
205 'pdf_url': pdf_url,
206 }
207 )
208
209 # parse suggestion
210 for suggestion in eval_xpath(dom, '//div[contains(@class, "gs_qsuggest_wrap")]//li//a'):
211 # append suggestion
212 results.append({'suggestion': extract_text(suggestion)})
213
214 for correction in eval_xpath(dom, '//div[@class="gs_r gs_pda"]/a'):
215 results.append({'correction': extract_text(correction)})
216
217 return results
parse_gs_a(Optional[str] text)