.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
mojeek.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2"""Mojeek (general, images, news)"""
3
4from typing import TYPE_CHECKING
5
6from datetime import datetime
7from urllib.parse import urlencode
8from lxml import html
9
10from dateutil.relativedelta import relativedelta
11from searx.utils import eval_xpath, eval_xpath_list, extract_text
12from searx.enginelib.traits import EngineTraits
13
14about = {
15 'website': 'https://mojeek.com',
16 'wikidata_id': 'Q60747299',
17 'official_api_documentation': 'https://www.mojeek.com/support/api/search/request_parameters.html',
18 'use_official_api': False,
19 'require_api_key': False,
20 'results': 'HTML',
21}
22paging = True # paging is only supported for general search
23safesearch = True
24time_range_support = True # time range search is supported for general and news
25max_page = 10
26
27base_url = "https://www.mojeek.com"
28
29categories = ["general", "web"]
30search_type = "" # leave blank for general, other possible values: images, news
31
32results_xpath = '//ul[@class="results-standard"]/li/a[@class="ob"]'
33url_xpath = './@href'
34title_xpath = '../h2/a'
35content_xpath = '..//p[@class="s"]'
36suggestion_xpath = '//div[@class="top-info"]/p[@class="top-info spell"]/em/a'
37
38image_results_xpath = '//div[@id="results"]/div[contains(@class, "image")]'
39image_url_xpath = './a/@href'
40image_title_xpath = './a/@data-title'
41image_img_src_xpath = './a/img/@src'
42
43news_results_xpath = '//section[contains(@class, "news-search-result")]//article'
44news_url_xpath = './/h2/a/@href'
45news_title_xpath = './/h2/a'
46news_content_xpath = './/p[@class="s"]'
47
48language_param = 'lb'
49region_param = 'arc'
50
51_delta_kwargs = {'day': 'days', 'week': 'weeks', 'month': 'months', 'year': 'years'}
52
53if TYPE_CHECKING:
54 import logging
55
56 logger = logging.getLogger()
57
58traits: EngineTraits
59
60
61def init(_):
62 if search_type not in ('', 'images', 'news'):
63 raise ValueError(f"Invalid search type {search_type}")
64
65
66def request(query, params):
67 args = {
68 'q': query,
69 'safe': min(params['safesearch'], 1),
70 language_param: traits.get_language(params['searxng_locale'], traits.custom['language_all']),
71 region_param: traits.get_region(params['searxng_locale'], traits.custom['region_all']),
72 }
73
74 if search_type:
75 args['fmt'] = search_type
76
77 if search_type == '':
78 args['s'] = 10 * (params['pageno'] - 1)
79
80 if params['time_range'] and search_type != 'images':
81 kwargs = {_delta_kwargs[params['time_range']]: 1}
82 args["since"] = (datetime.now() - relativedelta(**kwargs)).strftime("%Y%m%d") # type: ignore
83 logger.debug(args["since"])
84
85 params['url'] = f"{base_url}/search?{urlencode(args)}"
86
87 return params
88
89
91 results = []
92
93 for result in eval_xpath_list(dom, results_xpath):
94 results.append(
95 {
96 'url': extract_text(eval_xpath(result, url_xpath)),
97 'title': extract_text(eval_xpath(result, title_xpath)),
98 'content': extract_text(eval_xpath(result, content_xpath)),
99 }
100 )
101
102 for suggestion in eval_xpath(dom, suggestion_xpath):
103 results.append({'suggestion': extract_text(suggestion)})
104
105 return results
106
107
109 results = []
110
111 for result in eval_xpath_list(dom, image_results_xpath):
112 results.append(
113 {
114 'template': 'images.html',
115 'url': extract_text(eval_xpath(result, image_url_xpath)),
116 'title': extract_text(eval_xpath(result, image_title_xpath)),
117 'img_src': base_url + extract_text(eval_xpath(result, image_img_src_xpath)), # type: ignore
118 'content': '',
119 }
120 )
121
122 return results
123
124
126 results = []
127
128 for result in eval_xpath_list(dom, news_results_xpath):
129 results.append(
130 {
131 'url': extract_text(eval_xpath(result, news_url_xpath)),
132 'title': extract_text(eval_xpath(result, news_title_xpath)),
133 'content': extract_text(eval_xpath(result, news_content_xpath)),
134 }
135 )
136
137 return results
138
139
140def response(resp):
141 dom = html.fromstring(resp.text)
142
143 if search_type == '':
144 return _general_results(dom)
145
146 if search_type == 'images':
147 return _image_results(dom)
148
149 if search_type == 'news':
150 return _news_results(dom)
151
152 raise ValueError(f"Invalid search type {search_type}")
153
154
155def fetch_traits(engine_traits: EngineTraits):
156 # pylint: disable=import-outside-toplevel
157 from searx import network
158 from searx.locales import get_official_locales, region_tag
159 from babel import Locale, UnknownLocaleError
160 import contextlib
161
162 resp = network.get(base_url + "/preferences", headers={'Accept-Language': 'en-US,en;q=0.5'})
163 dom = html.fromstring(resp.text) # type: ignore
164
165 languages = eval_xpath_list(dom, f'//select[@name="{language_param}"]/option/@value')
166
167 engine_traits.custom['language_all'] = languages[0]
168
169 for code in languages[1:]:
170 with contextlib.suppress(UnknownLocaleError):
171 locale = Locale(code)
172 engine_traits.languages[locale.language] = code
173
174 regions = eval_xpath_list(dom, f'//select[@name="{region_param}"]/option/@value')
175
176 engine_traits.custom['region_all'] = regions[1]
177
178 for code in regions[2:]:
179 for locale in get_official_locales(code, engine_traits.languages):
180 engine_traits.regions[region_tag(locale)] = code
request(query, params)
Definition mojeek.py:66
fetch_traits(EngineTraits engine_traits)
Definition mojeek.py:155