1
0
mirror of https://github.com/searxng/searxng.git synced 2024-11-23 12:31:25 +01:00
searxng/searx/engines/twitter.py

78 lines
2.2 KiB
Python
Raw Normal View History

## 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
2013-10-20 10:40:02 +02:00
from urlparse import urljoin
from urllib import urlencode
from lxml import html
from datetime import datetime
from searx.engines.xpath import extract_text
2013-10-20 10:40:02 +02:00
# engine dependent config
2013-10-20 10:40:02 +02:00
categories = ['social media']
language_support = True
2013-10-20 10:40:02 +02:00
# search-url
2013-10-20 10:40:02 +02:00
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")]'
2014-01-20 02:31:20 +01:00
2013-10-20 10:40:02 +02:00
# do search-request
2013-10-20 10:40:02 +02:00
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'
2013-10-20 10:40:02 +02:00
return params
# get response from search-request
2013-10-20 10:40:02 +02:00
def response(resp):
results = []
2013-10-20 10:40:02 +02:00
dom = html.fromstring(resp.text)
# parse results
for tweet in dom.xpath(results_xpath):
link = tweet.xpath(link_xpath)[0]
2013-10-20 10:40:02 +02:00
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
2013-10-20 10:40:02 +02:00
return results