summaryrefslogtreecommitdiff
path: root/searx/engines/twitter.py
blob: 0e35e6188721e2374ac356dedb00b2f9010dfefd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
## Twitter (Social media)
#
# @website     https://twitter.com/
# @provide-api yes (https://dev.twitter.com/docs/using-search)
#
# @using-api   no
# @results     HTML (using search portal)
# @stable      no (HTML can change)
# @parse       url, title, content
#
# @todo        publishedDate

from urlparse import urljoin
from urllib import urlencode
from lxml import html
from datetime import datetime
from searx.engines.xpath import extract_text

# engine dependent config
categories = ['social media']
language_support = True

# search-url
base_url = 'https://twitter.com/'
search_url = base_url + 'search?'

# specific xpath variables
results_xpath = '//li[@data-item-type="tweet"]'
link_xpath = './/small[@class="time"]//a'
title_xpath = './/span[@class="username js-action-profile-name"]'
content_xpath = './/p[@class="js-tweet-text tweet-text"]'
timestamp_xpath = './/span[contains(@class,"_timestamp")]'


# do search-request
def request(query, params):
    params['url'] = search_url + urlencode({'q': query})

    # set language if specified
    if params['language'] != 'all':
        params['cookies']['lang'] = params['language'].split('_')[0]
    else:
        params['cookies']['lang'] = 'en'

    return params


# get response from search-request
def response(resp):
    results = []

    dom = html.fromstring(resp.text)

    # parse results
    for tweet in dom.xpath(results_xpath):
        link = tweet.xpath(link_xpath)[0]
        url = urljoin(base_url, link.attrib.get('href'))
        title = extract_text(tweet.xpath(title_xpath))
        content = extract_text(tweet.xpath(content_xpath)[0])

        pubdate = tweet.xpath(timestamp_xpath)
        if len(pubdate) > 0:
            timestamp = float(pubdate[0].attrib.get('data-time'))
            publishedDate = datetime.fromtimestamp(timestamp, None)
            # append result
            results.append({'url': url,
                            'title': title,
                            'content': content,
                            'publishedDate': publishedDate})
        else:
            # append result
            results.append({'url': url,
                            'title': title,
                            'content': content})

    # return results
    return results