searxng/searx/engines/google_news.py

86 lines
2.2 KiB
Python
Raw Normal View History

"""
Google (News)
@website https://news.google.com
@provide-api no
@using-api no
@results HTML
@stable no
@parse url, title, content, publishedDate
"""
2014-03-04 12:11:04 +00:00
from lxml import html
from searx.engines.google import _fetch_supported_languages, supported_languages_url
2016-11-30 17:43:03 +00:00
from searx.url_utils import urlencode
from searx.utils import match_language
2014-03-04 12:11:04 +00:00
2014-09-01 13:10:05 +00:00
# search-url
2014-03-04 12:11:04 +00:00
categories = ['news']
2014-09-01 13:10:05 +00:00
paging = True
language_support = True
safesearch = True
time_range_support = True
number_of_results = 10
2014-03-04 12:11:04 +00:00
search_url = 'https://www.google.com/search'\
'?{query}'\
'&tbm=nws'\
'&gws_rd=cr'\
'&{search_options}'
time_range_attr = "qdr:{range}"
time_range_dict = {'day': 'd',
'week': 'w',
'month': 'm',
'year': 'y'}
2014-03-04 12:11:04 +00:00
2014-09-01 13:10:05 +00:00
# do search-request
2014-03-04 12:11:04 +00:00
def request(query, params):
2014-09-01 13:10:05 +00:00
search_options = {
'start': (params['pageno'] - 1) * number_of_results
}
if params['time_range'] in time_range_dict:
search_options['tbs'] = time_range_attr.format(range=time_range_dict[params['time_range']])
if safesearch and params['safesearch']:
search_options['safe'] = 'on'
2014-09-01 13:10:05 +00:00
params['url'] = search_url.format(query=urlencode({'q': query}),
search_options=urlencode(search_options))
language = match_language(params['language'], supported_languages).split('-')[0]
if language:
params['url'] += '&lr=lang_' + language
2014-09-01 13:10:05 +00:00
2014-03-04 12:11:04 +00:00
return params
2014-09-01 13:10:05 +00:00
# get response from search-request
2014-03-04 12:11:04 +00:00
def response(resp):
results = []
2014-09-01 13:10:05 +00:00
dom = html.fromstring(resp.text)
2014-03-04 12:11:04 +00:00
2014-09-01 13:10:05 +00:00
# parse results
for result in dom.xpath('//div[@class="g"]|//div[@class="g _cy"]'):
try:
r = {
2017-08-31 15:48:07 +00:00
'url': result.xpath('.//a[@class="l _PMs"]')[0].attrib.get("href"),
'title': ''.join(result.xpath('.//a[@class="l _PMs"]//text()')),
'content': ''.join(result.xpath('.//div[@class="st"]//text()')),
}
except:
continue
imgs = result.xpath('.//img/@src')
if len(imgs) and not imgs[0].startswith('data'):
r['img_src'] = imgs[0]
results.append(r)
2014-09-01 13:10:05 +00:00
# return results
2014-03-04 12:11:04 +00:00
return results