.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
searx.engines.google_scholar Namespace Reference

Functions

 time_range_args (params)
 
 detect_google_captcha (dom)
 
 request (query, params)
 
 parse_gs_a (Optional[str] text)
 
 response (resp)
 

Variables

logging logger .Logger
 
dict about
 
list categories = ['science', 'scientific publications']
 
bool paging = True
 
int max_page = 50
 
bool language_support = True
 
bool time_range_support = True
 
bool safesearch = False
 
bool send_accept_language_header = True
 

Detailed Description

This is the implementation of the Google Scholar engine.

Compared to other Google services the Scholar engine has a simple GET REST-API
and there does not exists `async` API.  Even though the API slightly vintage we
can make use of the :ref:`google API` to assemble the arguments of the GET
request.

Function Documentation

◆ detect_google_captcha()

searx.engines.google_scholar.detect_google_captcha ( dom)
In case of CAPTCHA Google Scholar open its own *not a Robot* dialog and is
not redirected to ``sorry.google.com``.

Definition at line 84 of file google_scholar.py.

84def detect_google_captcha(dom):
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']"):
89 raise SearxEngineCaptchaException()
90
91

◆ parse_gs_a()

searx.engines.google_scholar.parse_gs_a ( Optional[str] text)
Parse the text written in green.

Possible formats:
* "{authors} - {journal}, {year} - {publisher}"
* "{authors} - {year} - {publisher}"
* "{authors} - {publisher}"

Definition at line 114 of file google_scholar.py.

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

◆ request()

searx.engines.google_scholar.request ( query,
params )
Google-Scholar search request

Definition at line 92 of file google_scholar.py.

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

References searx.engines.google_scholar.time_range_args().

+ Here is the call graph for this function:

◆ response()

searx.engines.google_scholar.response ( resp)
Parse response from Google Scholar

Definition at line 150 of file google_scholar.py.

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

◆ time_range_args()

searx.engines.google_scholar.time_range_args ( params)
Returns a dictionary with a time range arguments based on
``params['time_range']``.

Google Scholar supports a detailed search by year.  Searching by *last
month* or *last week* (as offered by SearXNG) is uncommon for scientific
publications and is not supported by Google Scholar.

To limit the result list when the users selects a range, all the SearXNG
ranges (*day*, *week*, *month*, *year*) are mapped to *year*.  If no range
is set an empty dictionary of arguments is returned.  Example;  when
user selects a time range (current year minus one in 2022):

.. code:: python

    { 'as_ylo' : 2021 }

Definition at line 60 of file google_scholar.py.

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

Referenced by searx.engines.google_scholar.request().

+ Here is the caller graph for this function:

Variable Documentation

◆ about

dict searx.engines.google_scholar.about
Initial value:
1= {
2 "website": 'https://scholar.google.com',
3 "wikidata_id": 'Q494817',
4 "official_api_documentation": 'https://developers.google.com/custom-search',
5 "use_official_api": False,
6 "require_api_key": False,
7 "results": 'HTML',
8}

Definition at line 41 of file google_scholar.py.

◆ categories

list searx.engines.google_scholar.categories = ['science', 'scientific publications']

Definition at line 51 of file google_scholar.py.

◆ language_support

bool searx.engines.google_scholar.language_support = True

Definition at line 54 of file google_scholar.py.

◆ logger

logging searx.engines.google_scholar.logger .Logger

Definition at line 36 of file google_scholar.py.

◆ max_page

int searx.engines.google_scholar.max_page = 50

Definition at line 53 of file google_scholar.py.

◆ paging

bool searx.engines.google_scholar.paging = True

Definition at line 52 of file google_scholar.py.

◆ safesearch

bool searx.engines.google_scholar.safesearch = False

Definition at line 56 of file google_scholar.py.

◆ send_accept_language_header

bool searx.engines.google_scholar.send_accept_language_header = True

Definition at line 57 of file google_scholar.py.

◆ time_range_support

bool searx.engines.google_scholar.time_range_support = True

Definition at line 55 of file google_scholar.py.