twitter.py 994B

1234567891011121314151617181920212223242526272829303132
  1. from urlparse import urljoin
  2. from urllib import urlencode
  3. from lxml import html
  4. from cgi import escape
  5. categories = ['social media']
  6. base_url = 'https://twitter.com/'
  7. search_url = base_url+'search?'
  8. title_xpath = './/span[@class="username js-action-profile-name"]//text()'
  9. content_xpath = './/p[@class="js-tweet-text tweet-text"]//text()'
  10. def request(query, params):
  11. global search_url
  12. params['url'] = search_url + urlencode({'q': query})
  13. return params
  14. def response(resp):
  15. global base_url
  16. results = []
  17. dom = html.fromstring(resp.text)
  18. for tweet in dom.xpath('//li[@data-item-type="tweet"]'):
  19. link = tweet.xpath('.//small[@class="time"]//a')[0]
  20. url = urljoin(base_url, link.attrib.get('href'))
  21. title = ''.join(tweet.xpath(title_xpath))
  22. content = escape(''.join(tweet.xpath(content_xpath)))
  23. results.append({'url': url,
  24. 'title': title,
  25. 'content': content})
  26. return results