searxngRebrandZaclys/searx/engines/duckduckgo.py

86 lines
2.1 KiB
Python
Raw Normal View History

"""
DuckDuckGo (Web)
@website https://duckduckgo.com/
@provide-api yes (https://duckduckgo.com/api),
but not all results from search-site
@using-api no
@results HTML (using search portal)
@stable no (HTML can change)
@parse url, title, content
@todo rewrite to api
"""
2013-10-23 21:55:37 +00:00
from urllib import urlencode
2014-03-21 15:33:17 +00:00
from lxml.html import fromstring
2015-02-02 16:55:39 +00:00
from searx.engines.xpath import extract_text
2013-10-14 21:09:13 +00:00
# engine dependent config
categories = ['general']
paging = True
language_support = True
2013-10-14 21:09:13 +00:00
# search-url
url = 'https://duckduckgo.com/html?{query}&s={offset}'
# specific xpath variables
result_xpath = '//div[@class="result results_links results_links_deep web-result "]' # noqa
url_xpath = './/a[@class="result__a"]/@href'
title_xpath = './/a[@class="result__a"]'
content_xpath = './/a[@class="result__snippet"]'
2014-03-29 15:38:45 +00:00
# do search-request
2013-10-14 21:09:13 +00:00
def request(query, params):
2014-01-30 00:03:19 +00:00
offset = (params['pageno'] - 1) * 30
if params['language'] == 'all':
locale = None
else:
locale = params['language'].split('_')
if len(locale) == 2:
# country code goes first
locale = locale[1].lower() + '-' + locale[0].lower()
else:
# doesn't actually do anything because ddg requires both country and language
locale = locale[0].lower()
if locale:
params['url'] = url.format(
query=urlencode({'q': query, 'kl': locale}), offset=offset)
else:
params['url'] = url.format(
query=urlencode({'q': query}), offset=offset)
2013-10-14 21:09:13 +00:00
return params
# get response from search-request
2013-10-14 21:09:13 +00:00
def response(resp):
2013-10-15 17:11:43 +00:00
results = []
2014-03-21 15:33:17 +00:00
doc = fromstring(resp.text)
2014-09-02 16:12:42 +00:00
# parse results
2014-03-21 15:33:17 +00:00
for r in doc.xpath(result_xpath):
2014-03-21 17:17:13 +00:00
try:
res_url = r.xpath(url_xpath)[-1]
except:
continue
2014-03-21 15:33:17 +00:00
if not res_url:
2013-10-15 17:11:43 +00:00
continue
2015-02-02 16:55:39 +00:00
title = extract_text(r.xpath(title_xpath))
content = extract_text(r.xpath(content_xpath))
# append result
2014-03-21 15:33:17 +00:00
results.append({'title': title,
'content': content,
2015-09-07 21:13:04 +00:00
'url': res_url})
2014-03-21 15:33:17 +00:00
# return results
2013-10-15 17:11:43 +00:00
return results