on master help sign in
[mod] move extract_text, extract_url to searx.utils
commit2006eb468087c045c46c7d9e1d771e8ab2dfed7b authorAlexandre Flament <alex@al-f.net> dateFri 2 Oct 2020, 18:13 (6 years ago) parentecb9f28
39 files changed+156−137
searx/engines/1337x.py+1−2 searx/engines/acgsou.py+1−2 searx/engines/apkmirror.py+1−1 searx/engines/archlinux.py+1−1 searx/engines/bing.py+1−2 searx/engines/btdigg.py+1−2 searx/engines/deviantart.py+1−1 searx/engines/digbt.py+1−2 searx/engines/doku.py+1−2 searx/engines/duckduckgo.py+1−2 searx/engines/duckduckgo_definitions.py+1−2 searx/engines/duckduckgo_images.py+1−1 searx/engines/duden.py+1−2 searx/engines/etools.py+1−2 searx/engines/fdroid.py+1−1 searx/engines/framalibre.py+1−1 searx/engines/gentoo.py+1−1 searx/engines/google.py+1−2 searx/engines/google_images.py+1−2 searx/engines/google_videos.py+1−1 searx/engines/ina.py+1−1 searx/engines/kickass.py+1−2 searx/engines/nyaa.py+1−2 searx/engines/piratebay.py+1−2 searx/engines/seedpeer.py+1−1 searx/engines/stackoverflow.py+1−1 searx/engines/startpage.py+1−2 searx/engines/tokyotoshokan.py+1−2 searx/engines/torrentz.py+1−2 searx/engines/twitter.py+1−1 searx/engines/wikidata.py+1−2 searx/engines/www1x.py+1−1 searx/engines/xpath.py+2−73 searx/engines/yahoo.py+1−2 searx/engines/yahoo_news.py+1−2 searx/engines/yggtorrent.py+1−2 searx/engines/youtube_noapi.py+1−2 searx/utils.py+73−1 tests/unit/test_utils.py+45−4
searx/engines/1337x.py+1−2
@@ -1,7 +1,6 @@
11from urllib.parse import quote, urljoin
22from lxml import html
3−from searx.engines.xpath import extract_text
4−from searx.utils import get_torrent_size
3+from searx.utils import extract_text, get_torrent_size
54
65
76url = 'https://1337x.to/'
searx/engines/acgsou.py+1−2
@@ -11,8 +11,7 @@
1111
1212from urllib.parse import urlencode
1313from lxml import html
14−from searx.engines.xpath import extract_text
15−from searx.utils import get_torrent_size, int_or_zero
14+from searx.utils import extract_text, get_torrent_size, int_or_zero
1615
1716# engine dependent config
1817categories = ['files', 'images', 'videos', 'music']
searx/engines/apkmirror.py+1−1
@@ -11,7 +11,7 @@
1111
1212from urllib.parse import urlencode
1313from lxml import html
14−from searx.engines.xpath import extract_text
14+from searx.utils import extract_text
1515
1616
1717# engine dependent config
searx/engines/archlinux.py+1−1
@@ -13,7 +13,7 @@
1313
1414from urllib.parse import urlencode, urljoin
1515from lxml import html
16−from searx.engines.xpath import extract_text
16+from searx.utils import extract_text
1717
1818# engine dependent config
1919categories = ['it']
searx/engines/bing.py+1−2
@@ -17,8 +17,7 @@ import re
1717from urllib.parse import urlencode
1818from lxml import html
1919from searx import logger, utils
20−from searx.engines.xpath import extract_text
21−from searx.utils import match_language, gen_useragent, eval_xpath
20+from searx.utils import extract_text, match_language, gen_useragent, eval_xpath
2221
2322logger = logger.getChild('bing engine')
2423
searx/engines/btdigg.py+1−2
@@ -13,8 +13,7 @@
1313from lxml import html
1414from operator import itemgetter
1515from urllib.parse import quote, urljoin
16−from searx.engines.xpath import extract_text
17−from searx.utils import get_torrent_size
16+from searx.utils import extract_text, get_torrent_size
1817
1918# engine dependent config
2019categories = ['videos', 'music', 'files']
searx/engines/deviantart.py+1−1
@@ -15,7 +15,7 @@
1515from lxml import html
1616import re
1717from urllib.parse import urlencode
18−from searx.engines.xpath import extract_text
18+from searx.utils import extract_text
1919
2020
2121# engine dependent config
searx/engines/digbt.py+1−2
@@ -12,8 +12,7 @@
1212
1313from urllib.parse import urljoin
1414from lxml import html
15−from searx.engines.xpath import extract_text
16−from searx.utils import get_torrent_size
15+from searx.utils import extract_text, get_torrent_size
1716
1817
1918categories = ['videos', 'music', 'files']
searx/engines/doku.py+1−2
@@ -11,8 +11,7 @@
1111
1212from urllib.parse import urlencode
1313from lxml.html import fromstring
14−from searx.engines.xpath import extract_text
15−from searx.utils import eval_xpath
14+from searx.utils import extract_text, eval_xpath
1615
1716# engine dependent config
1817categories = ['general'] # TODO , 'images', 'music', 'videos', 'files'
searx/engines/duckduckgo.py+1−2
@@ -16,9 +16,8 @@
1616from lxml.html import fromstring
1717from json import loads
1818from urllib.parse import urlencode
19−from searx.engines.xpath import extract_text
2019from searx.poolrequests import get
21−from searx.utils import match_language, eval_xpath
20+from searx.utils import extract_text, match_language, eval_xpath
2221
2322# engine dependent config
2423categories = ['general']
searx/engines/duckduckgo_definitions.py+1−2
@@ -13,9 +13,8 @@ import json
1313from urllib.parse import urlencode
1414from lxml import html
1515from re import compile
16−from searx.engines.xpath import extract_text
1716from searx.engines.duckduckgo import _fetch_supported_languages, supported_languages_url, language_aliases
18−from searx.utils import html_to_text, match_language
17+from searx.utils import extract_text, html_to_text, match_language
1918
2019url = 'https://api.duckduckgo.com/'\
2120 + '?{query}&format=json&pretty=0&no_redirect=1&d=1'
searx/engines/duckduckgo_images.py+1−1
@@ -15,12 +15,12 @@
1515
1616from json import loads
1717from urllib.parse import urlencode
18−from searx.engines.xpath import extract_text
1918from searx.engines.duckduckgo import (
2019 _fetch_supported_languages, supported_languages_url,
2120 get_region_code, language_aliases
2221)
2322from searx.poolrequests import get
23+from searx.utils import extract_text
2424
2525# engine dependent config
2626categories = ['images']
searx/engines/duden.py+1−2
@@ -11,8 +11,7 @@
1111from lxml import html, etree
1212import re
1313from urllib.parse import quote, urljoin
14−from searx.engines.xpath import extract_text
15−from searx.utils import eval_xpath
14+from searx.utils import extract_text, eval_xpath
1615from searx import logger
1716
1817categories = ['general']
searx/engines/etools.py+1−2
@@ -11,8 +11,7 @@
1111
1212from lxml import html
1313from urllib.parse import quote
14−from searx.engines.xpath import extract_text
15−from searx.utils import eval_xpath
14+from searx.utils import extract_text, eval_xpath
1615
1716categories = ['general']
1817paging = False
searx/engines/fdroid.py+1−1
@@ -11,7 +11,7 @@
1111
1212from urllib.parse import urlencode
1313from lxml import html
14−from searx.engines.xpath import extract_text
14+from searx.utils import extract_text
1515
1616# engine dependent config
1717categories = ['files']
searx/engines/framalibre.py+1−1
@@ -13,7 +13,7 @@
1313from html import escape
1414from urllib.parse import urljoin, urlencode
1515from lxml import html
16−from searx.engines.xpath import extract_text
16+from searx.utils import extract_text
1717
1818# engine dependent config
1919categories = ['it']
searx/engines/gentoo.py+1−1
@@ -13,7 +13,7 @@
1313
1414from urllib.parse import urlencode, urljoin
1515from lxml import html
16−from searx.engines.xpath import extract_text
16+from searx.utils import extract_text
1717
1818# engine dependent config
1919categories = ['it']
searx/engines/google.py+1−2
@@ -21,9 +21,8 @@ Definitions`_.
2121from urllib.parse import urlencode, urlparse
2222from lxml import html
2323from flask_babel import gettext
24−from searx.engines.xpath import extract_text
2524from searx import logger
26−from searx.utils import match_language, eval_xpath
25+from searx.utils import match_language, extract_text, eval_xpath
2726
2827logger = logger.getChild('google engine')
2928
searx/engines/google_images.py+1−2
@@ -28,8 +28,7 @@ from urllib.parse import urlencode, urlparse, unquote
2828from lxml import html
2929from flask_babel import gettext
3030from searx import logger
31−from searx.utils import eval_xpath
32−from searx.engines.xpath import extract_text
31+from searx.utils import extract_text, eval_xpath
3332
3433# pylint: disable=unused-import
3534from searx.engines.google import (
searx/engines/google_videos.py+1−1
@@ -14,7 +14,7 @@ from datetime import date, timedelta
1414from json import loads
1515from urllib.parse import urlencode
1616from lxml import html
17−from searx.engines.xpath import extract_text
17+from searx.utils import extract_text
1818import re
1919
2020# engine dependent config
searx/engines/ina.py+1−1
@@ -16,7 +16,7 @@ from urllib.parse import urlencode
1616from lxml import html
1717from dateutil import parser
1818from html.parser import HTMLParser
19−from searx.engines.xpath import extract_text
19+from searx.utils import extract_text
2020
2121
2222# engine dependent config
searx/engines/kickass.py+1−2
@@ -13,8 +13,7 @@
1313from lxml import html
1414from operator import itemgetter
1515from urllib.parse import quote, urljoin
16−from searx.engines.xpath import extract_text
17−from searx.utils import get_torrent_size, convert_str_to_int
16+from searx.utils import extract_text, get_torrent_size, convert_str_to_int
1817
1918# engine dependent config
2019categories = ['videos', 'music', 'files']
searx/engines/nyaa.py+1−2
@@ -11,8 +11,7 @@
1111
1212from lxml import html
1313from urllib.parse import urlencode
14−from searx.engines.xpath import extract_text
15−from searx.utils import get_torrent_size, int_or_zero
14+from searx.utils import extract_text, get_torrent_size, int_or_zero
1615
1716# engine dependent config
1817categories = ['files', 'images', 'videos', 'music']
searx/engines/piratebay.py+1−2
@@ -13,8 +13,7 @@ from datetime import datetime
1313from operator import itemgetter
1414
1515from urllib.parse import quote, urljoin
16−from searx.engines.xpath import extract_text
17−from searx.utils import get_torrent_size
16+from searx.utils import extract_text, get_torrent_size
1817
1918# engine dependent config
2019categories = ["videos", "music", "files"]
searx/engines/seedpeer.py+1−1
@@ -12,7 +12,7 @@ from lxml import html
1212from json import loads
1313from operator import itemgetter
1414from urllib.parse import quote, urljoin
15−from searx.engines.xpath import extract_text
15+from searx.utils import extract_text
1616
1717
1818url = 'https://seedpeer.me/'
searx/engines/stackoverflow.py+1−1
@@ -12,7 +12,7 @@
1212
1313from urllib.parse import urlencode, urljoin
1414from lxml import html
15−from searx.engines.xpath import extract_text
15+from searx.utils import extract_text
1616
1717# engine dependent config
1818categories = ['it']
searx/engines/startpage.py+1−2
@@ -17,9 +17,8 @@ import re
1717from unicodedata import normalize, combining
1818from babel import Locale
1919from babel.localedata import locale_identifiers
20−from searx.engines.xpath import extract_text
2120from searx.languages import language_codes
22−from searx.utils import eval_xpath, match_language
21+from searx.utils import extract_text, eval_xpath, match_language
2322
2423# engine dependent config
2524categories = ['general']
searx/engines/tokyotoshokan.py+1−2
@@ -13,9 +13,8 @@
1313import re
1414from urllib.parse import urlencode
1515from lxml import html
16−from searx.engines.xpath import extract_text
1716from datetime import datetime
18−from searx.utils import get_torrent_size, int_or_zero
17+from searx.utils import extract_text, get_torrent_size, int_or_zero
1918
2019# engine dependent config
2120categories = ['files', 'videos', 'music']
searx/engines/torrentz.py+1−2
@@ -15,8 +15,7 @@ import re
1515from urllib.parse import urlencode
1616from lxml import html
1717from datetime import datetime
18−from searx.engines.xpath import extract_text
19−from searx.utils import get_torrent_size
18+from searx.utils import extract_text, get_torrent_size
2019
2120# engine dependent config
2221categories = ['files', 'videos', 'music']
searx/engines/twitter.py+1−1
@@ -15,7 +15,7 @@
1515from urllib.parse import urlencode, urljoin
1616from lxml import html
1717from datetime import datetime
18−from searx.engines.xpath import extract_text
18+from searx.utils import extract_text
1919
2020# engine dependent config
2121categories = ['social media']
searx/engines/wikidata.py+1−2
@@ -13,9 +13,8 @@
1313
1414from searx import logger
1515from searx.poolrequests import get
16−from searx.engines.xpath import extract_text
1716from searx.engines.wikipedia import _fetch_supported_languages, supported_languages_url
18−from searx.utils import match_language, eval_xpath
17+from searx.utils import extract_text, match_language, eval_xpath
1918
2019from urllib.parse import urlencode
2120from json import loads
searx/engines/www1x.py+1−1
@@ -12,7 +12,7 @@
1212
1313from lxml import html
1414from urllib.parse import urlencode, urljoin
15−from searx.engines.xpath import extract_text
15+from searx.utils import extract_text
1616
1717# engine dependent config
1818categories = ['images']
searx/engines/xpath.py+2−73
@@ -1,7 +1,6 @@
1−from urllib.parse import unquote, urlencode, urljoin, urlparse
21from lxml import html
3−from lxml.etree import _ElementStringResult, _ElementUnicodeResult
4−from searx.utils import html_to_text, eval_xpath
2+from urllib.parse import urlencode
3+from searx.utils import extract_text, extract_url, eval_xpath
54
65search_url = None
76url_xpath = None
@@ -21,76 +20,6 @@ page_size = 1
2120first_page_num = 1
2221
2322
24−'''
25−if xpath_results is list, extract the text from each result and concat the list
26−if xpath_results is a xml element, extract all the text node from it
27− ( text_content() method from lxml )
28−if xpath_results is a string element, then it's already done
29−'''
30−
31−
32−def extract_text(xpath_results):
33− if type(xpath_results) == list:
34− # it's list of result : concat everything using recursive call
35− result = ''
36− for e in xpath_results:
37− result = result + extract_text(e)
38− return result.strip()
39− elif type(xpath_results) in [_ElementStringResult, _ElementUnicodeResult]:
40− # it's a string
41− return ''.join(xpath_results)
42− else:
43− # it's a element
44− text = html.tostring(
45− xpath_results, encoding='unicode', method='text', with_tail=False
46− )
47− text = text.strip().replace('\n', ' ')
48− return ' '.join(text.split())
49−
50−
51−def extract_url(xpath_results, search_url):
52− if xpath_results == []:
53− raise Exception('Empty url resultset')
54− url = extract_text(xpath_results)
55−
56− if url.startswith('//'):
57− # add http or https to this kind of url //example.com/
58− parsed_search_url = urlparse(search_url)
59− url = '{0}:{1}'.format(parsed_search_url.scheme or 'http', url)
60− elif url.startswith('/'):
61− # fix relative url to the search engine
62− url = urljoin(search_url, url)
63−
64− # fix relative urls that fall through the crack
65− if '://' not in url:
66− url = urljoin(search_url, url)
67−
68− # normalize url
69− url = normalize_url(url)
70−
71− return url
72−
73−
74−def normalize_url(url):
75− parsed_url = urlparse(url)
76−
77− # add a / at this end of the url if there is no path
78− if not parsed_url.netloc:
79− raise Exception('Cannot parse url')
80− if not parsed_url.path:
81− url += '/'
82−
83− # FIXME : hack for yahoo
84− if parsed_url.hostname == 'search.yahoo.com'\
85− and parsed_url.path.startswith('/r'):
86− p = parsed_url.path
87− mark = p.find('/**')
88− if mark != -1:
89− return unquote(p[mark + 3:]).decode()
90−
91− return url
92−
93−
9423def request(query, params):
9524 query = urlencode({'q': query})[2:]
9625
searx/engines/yahoo.py+1−2
@@ -13,8 +13,7 @@
1313
1414from urllib.parse import unquote, urlencode
1515from lxml import html
16−from searx.engines.xpath import extract_text, extract_url
17−from searx.utils import match_language, eval_xpath
16+from searx.utils import extract_text, extract_url, match_language, eval_xpath
1817
1918# engine dependent config
2019categories = ['general']
searx/engines/yahoo_news.py+1−2
@@ -13,12 +13,11 @@ import re
1313from datetime import datetime, timedelta
1414from urllib.parse import urlencode
1515from lxml import html
16−from searx.engines.xpath import extract_text, extract_url
1716from searx.engines.yahoo import (
1817 parse_url, _fetch_supported_languages, supported_languages_url, language_aliases
1918)
2019from dateutil import parser
21−from searx.utils import match_language
20+from searx.utils import extract_text, extract_url, match_language
2221
2322# engine dependent config
2423categories = ['news']
searx/engines/yggtorrent.py+1−2
@@ -12,8 +12,7 @@ from lxml import html
1212from operator import itemgetter
1313from datetime import datetime
1414from urllib.parse import quote
15−from searx.engines.xpath import extract_text
16−from searx.utils import get_torrent_size
15+from searx.utils import extract_text, get_torrent_size
1716from searx.poolrequests import get as http_get
1817
1918# engine dependent config
searx/engines/youtube_noapi.py+1−2
@@ -11,8 +11,7 @@
1111from functools import reduce
1212from json import loads
1313from urllib.parse import quote_plus
14−from searx.engines.xpath import extract_text
15−from searx.utils import list_get
14+from searx.utils import extract_text, list_get
1615
1716# engine dependent config
1817categories = ['videos', 'music']
searx/utils.py+73−1
@@ -10,9 +10,13 @@ from os.path import splitext, join
1010from io import open
1111from random import choice
1212from html.parser import HTMLParser
13−from lxml.etree import XPath
13+from urllib.parse import urljoin, urlparse, unquote
14+
15+from lxml import html
16+from lxml.etree import XPath, _ElementStringResult, _ElementUnicodeResult
1417from babel.core import get_global
1518
19+
1620from searx import settings
1721from searx.version import VERSION_STRING
1822from searx.languages import language_codes
@@ -106,6 +110,74 @@ def html_to_text(html):
106110 return s.get_text()
107111
108112
113+def extract_text(xpath_results):
114+ '''
115+ if xpath_results is list, extract the text from each result and concat the list
116+ if xpath_results is a xml element, extract all the text node from it
117+ ( text_content() method from lxml )
118+ if xpath_results is a string element, then it's already done
119+ '''
120+ if type(xpath_results) == list:
121+ # it's list of result : concat everything using recursive call
122+ result = ''
123+ for e in xpath_results:
124+ result = result + extract_text(e)
125+ return result.strip()
126+ elif type(xpath_results) in [_ElementStringResult, _ElementUnicodeResult]:
127+ # it's a string
128+ return ''.join(xpath_results)
129+ else:
130+ # it's a element
131+ text = html.tostring(
132+ xpath_results, encoding='unicode', method='text', with_tail=False
133+ )
134+ text = text.strip().replace('\n', ' ')
135+ return ' '.join(text.split())
136+
137+
138+def extract_url(xpath_results, search_url):
139+ if xpath_results == []:
140+ raise Exception('Empty url resultset')
141+ url = extract_text(xpath_results)
142+
143+ if url.startswith('//'):
144+ # add http or https to this kind of url //example.com/
145+ parsed_search_url = urlparse(search_url)
146+ url = '{0}:{1}'.format(parsed_search_url.scheme or 'http', url)
147+ elif url.startswith('/'):
148+ # fix relative url to the search engine
149+ url = urljoin(search_url, url)
150+
151+ # fix relative urls that fall through the crack
152+ if '://' not in url:
153+ url = urljoin(search_url, url)
154+
155+ # normalize url
156+ url = normalize_url(url)
157+
158+ return url
159+
160+
161+def normalize_url(url):
162+ parsed_url = urlparse(url)
163+
164+ # add a / at this end of the url if there is no path
165+ if not parsed_url.netloc:
166+ raise Exception('Cannot parse url')
167+ if not parsed_url.path:
168+ url += '/'
169+
170+ # FIXME : hack for yahoo
171+ if parsed_url.hostname == 'search.yahoo.com'\
172+ and parsed_url.path.startswith('/r'):
173+ p = parsed_url.path
174+ mark = p.find('/**')
175+ if mark != -1:
176+ return unquote(p[mark + 3:]).decode()
177+
178+ return url
179+
180+
109181def dict_subset(d, properties):
110182 result = {}
111183 for k in properties:
tests/unit/test_utils.py+45−4
@@ -1,4 +1,7 @@
11# -*- coding: utf-8 -*-
2+import lxml.etree
3+from lxml import html
4+
25from searx.testing import SearxTestCase
36from searx import utils
47
@@ -16,7 +19,30 @@ class TestUtils(SearxTestCase):
1619 self.assertTrue(utils.searx_useragent().startswith('searx'))
1720
1821 def test_html_to_text(self):
19− html = """
22+ html_str = """
23+ <a href="/testlink" class="link_access_account">
24+ <style>
25+ .toto {
26+ color: red;
27+ }
28+ </style>
29+ <span class="toto">
30+ <span>
31+ <img src="test.jpg" />
32+ </span>
33+ </span>
34+ <span class="titi">
35+ Test text
36+ </span>
37+ <script>value='dummy';</script>
38+ </a>
39+ """
40+ self.assertIsInstance(utils.html_to_text(html_str), str)
41+ self.assertIsNotNone(utils.html_to_text(html_str))
42+ self.assertEqual(utils.html_to_text(html_str), "Test text")
43+
44+ def test_extract_text(self):
45+ html_str = """
2046 <a href="/testlink" class="link_access_account">
2147 <span class="toto">
2248 <span>
@@ -28,9 +54,24 @@ class TestUtils(SearxTestCase):
2854 </span>
2955 </a>
3056 """
31− self.assertIsInstance(utils.html_to_text(html), str)
32− self.assertIsNotNone(utils.html_to_text(html))
33− self.assertEqual(utils.html_to_text(html), "Test text")
57+ dom = html.fromstring(html_str)
58+ self.assertEqual(utils.extract_text(dom), 'Test text')
59+ self.assertEqual(utils.extract_text(dom.xpath('//span')), 'Test text')
60+ self.assertEqual(utils.extract_text(dom.xpath('//img/@src')), 'test.jpg')
61+ self.assertEqual(utils.extract_text(dom.xpath('//unexistingtag')), '')
62+
63+ def test_extract_url(self):
64+ def f(html_str, search_url):
65+ return utils.extract_url(html.fromstring(html_str), search_url)
66+ self.assertEqual(f('<span id="42">https://example.com</span>', 'http://example.com/'), 'https://example.com/')
67+ self.assertEqual(f('https://example.com', 'http://example.com/'), 'https://example.com/')
68+ self.assertEqual(f('//example.com', 'http://example.com/'), 'http://example.com/')
69+ self.assertEqual(f('//example.com', 'https://example.com/'), 'https://example.com/')
70+ self.assertEqual(f('/path?a=1', 'https://example.com'), 'https://example.com/path?a=1')
71+ with self.assertRaises(lxml.etree.ParserError):
72+ f('', 'https://example.com')
73+ with self.assertRaises(Exception):
74+ utils.extract_url([], 'https://example.com')
3475
3576 def test_html_to_text_invalid(self):
3677 html = '<p><b>Lorem ipsum</i>dolor sit amet</p>'