Ver código fonte

[fix] google news engine change follow-up

Adam Tauber 8 anos atrás
pai
commit
a2c94895c1
2 arquivos alterados com 58 adições e 132 exclusões
  1. 46
    34
      searx/engines/google_news.py
  2. 12
    98
      tests/unit/engines/test_google_news.py

+ 46
- 34
searx/engines/google_news.py Ver arquivo

@@ -1,41 +1,56 @@
1 1
 """
2 2
  Google (News)
3 3
 
4
- @website     https://www.google.com
5
- @provide-api yes (https://developers.google.com/web-search/docs/),
6
-              deprecated!
4
+ @website     https://news.google.com
5
+ @provide-api no
7 6
 
8
- @using-api   yes
9
- @results     JSON
10
- @stable      yes (but deprecated)
7
+ @using-api   no
8
+ @results     HTML
9
+ @stable      no
11 10
  @parse       url, title, content, publishedDate
12 11
 """
13 12
 
13
+from lxml import html
14 14
 from urllib import urlencode
15
-from json import loads
16
-from dateutil import parser
17 15
 
18 16
 # search-url
19 17
 categories = ['news']
20 18
 paging = True
21 19
 language_support = True
20
+safesearch = True
21
+time_range_support = True
22
+number_of_results = 10
22 23
 
23
-# engine dependent config
24
-url = 'https://ajax.googleapis.com/'
25
-search_url = url + 'ajax/services/search/news?v=2.0&start={offset}&rsz=large&safe=off&filter=off&{query}&hl={lang}'
24
+search_url = 'https://www.google.com/search'\
25
+    '?{query}'\
26
+    '&tbm=nws'\
27
+    '&gws_rd=cr'\
28
+    '&{search_options}'
29
+time_range_attr = "qdr:{range}"
30
+time_range_dict = {'day': 'd',
31
+                   'week': 'w',
32
+                   'month': 'm'}
26 33
 
27 34
 
28 35
 # do search-request
29 36
 def request(query, params):
30
-    offset = (params['pageno'] - 1) * 8
31 37
 
32
-    language = 'en-US'
33
-    if params['language'] != 'all':
34
-        language = params['language'].replace('_', '-')
38
+    search_options = {
39
+        'start': (params['pageno'] - 1) * number_of_results
40
+    }
41
+
42
+    if params['time_range'] in time_range_dict:
43
+        search_options['tbs'] = time_range_attr.format(range=time_range_dict[params['time_range']])
44
+
45
+    if safesearch and params['safesearch']:
46
+        search_options['safe'] = 'on'
35 47
 
36
-    params['url'] = search_url.format(offset=offset,
37
-                                      query=urlencode({'q': query}),
38
-                                      lang=language)
48
+    params['url'] = search_url.format(query=urlencode({'q': query}),
49
+                                      search_options=urlencode(search_options))
50
+
51
+    if params['language'] != 'all':
52
+        language_array = params['language'].lower().split('_')
53
+        params['url'] += '&lr=lang_' + language_array[0]
39 54
 
40 55
     return params
41 56
 
@@ -44,24 +59,21 @@ def request(query, params):
44 59
 def response(resp):
45 60
     results = []
46 61
 
47
-    search_res = loads(resp.text)
48
-
49
-    # return empty array if there are no results
50
-    if not search_res.get('responseData', {}).get('results'):
51
-        return []
62
+    dom = html.fromstring(resp.text)
52 63
 
53 64
     # parse results
54
-    for result in search_res['responseData']['results']:
55
-        # parse publishedDate
56
-        publishedDate = parser.parse(result['publishedDate'])
57
-        if 'url' not in result:
58
-            continue
59
-
60
-        # append result
61
-        results.append({'url': result['unescapedUrl'],
62
-                        'title': result['titleNoFormatting'],
63
-                        'publishedDate': publishedDate,
64
-                        'content': result['content']})
65
+    for result in dom.xpath('//div[@class="g"]|//div[@class="g _cy"]'):
66
+        r = {
67
+            'url': result.xpath('.//div[@class="_cnc"]//a/@href')[0],
68
+            'title': ''.join(result.xpath('.//div[@class="_cnc"]//h3//text()')),
69
+            'content': ''.join(result.xpath('.//div[@class="st"]//text()')),
70
+        }
71
+
72
+        img = result.xpath('.//img/@src')[0]
73
+        if img and not img.startswith('data'):
74
+            r['img_src'] = img
75
+
76
+        results.append(r)
65 77
 
66 78
     # return results
67 79
     return results

+ 12
- 98
tests/unit/engines/test_google_news.py
Diferenças do arquivo suprimidas por serem muito extensas
Ver arquivo