twitter.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. ## Twitter (Social media)
  2. #
  3. # @website https://www.bing.com/news
  4. # @provide-api yes (https://dev.twitter.com/docs/using-search)
  5. #
  6. # @using-api no
  7. # @results HTML (using search portal)
  8. # @stable no (HTML can change)
  9. # @parse url, title, content
  10. #
  11. # @todo publishedDate
  12. from urlparse import urljoin
  13. from urllib import urlencode
  14. from lxml import html
  15. from cgi import escape
  16. # engine dependent config
  17. categories = ['social media']
  18. language_support = True
  19. # search-url
  20. base_url = 'https://twitter.com/'
  21. search_url = base_url+'search?'
  22. # specific xpath variables
  23. results_xpath = '//li[@data-item-type="tweet"]'
  24. link_xpath = './/small[@class="time"]//a'
  25. title_xpath = './/span[@class="username js-action-profile-name"]//text()'
  26. content_xpath = './/p[@class="js-tweet-text tweet-text"]//text()'
  27. # do search-request
  28. def request(query, params):
  29. params['url'] = search_url + urlencode({'q': query})
  30. # set language if specified
  31. if params['language'] != 'all':
  32. params['cookies']['lang'] = params['language'].split('_')[0]
  33. return params
  34. # get response from search-request
  35. def response(resp):
  36. results = []
  37. dom = html.fromstring(resp.text)
  38. # parse results
  39. for tweet in dom.xpath(results_xpath):
  40. link = tweet.xpath(link_xpath)[0]
  41. url = urljoin(base_url, link.attrib.get('href'))
  42. title = ''.join(tweet.xpath(title_xpath))
  43. content = escape(''.join(tweet.xpath(content_xpath)))
  44. # append result
  45. results.append({'url': url,
  46. 'title': title,
  47. 'content': content})
  48. # return results
  49. return results