Twitter search API

Twitter crawler 与sina 微博类似,使用twitter api之前,首先要有twitter的账号,在twitter developer中创建应用(https://apps.twitter.com/app/new)。

创建成功之后可以获得应用的信息,包括Consumer key和Consumer secret。并generate access token,将这四个数据保存下来,

接下来可以借助twitter api 进行twitter 抓取,现有的twitter api的python版本很多,这里主要介绍tweepy 以及python-twitter。

1. python-twitter

安装:在cmd 窗口中使用pip 命令:pip install python-twitter

安装成功后,可以运行如下代码:

import twitter

import optparse
import sys

def print_safe(string):
    """
    Format a string for safe printing
    """
    return string.encode(‘cp437‘, ‘xmlcharrefreplace‘)

def print_tweet(tweet):
    """
    Format and print `tweet`.
    """
    print "@" + print_safe( tweet.GetUser().GetScreenName() ) +      ": " + print_safe(tweet.GetText())

def search(search_term):
    """
    Print recent tweets containing `search_term`.
    """
    api = twitter.Api()
    tweets = api.GetSearch(search_term)
    for tweet in tweets:
        print_tweet(tweet)

def trending_topics():
    """
    Print the currently trending topics.
    """
    api = twitter.Api()
    trending_topics = api.GetTrendsCurrent()
    for topic in trending_topics:
        print print_safe(topic.name)

def user_tweets(username):
    """
    Print recent tweets by `username`.
    """
    api = twitter.Api()
    user_tweets = api.GetUserTimeline(screen_name=username)
    for tweet in user_tweets:
        print_tweet(tweet)

def trending_tweets():
    """
    Print tweets for all the trending topics.
    """
    api = twitter.Api()

    trending_topics = api.GetTrendsCurrent()
    tweets = []
    # To add some variety, let‘s round-robin through the trending
    # topics, displaying a tweet from each until we run out of tweets.
    for topic in trending_topics:
        tweets.append((topic, api.GetSearch(topic.name)))

    while True:
        for topic, topic_tweets in tweets:
            if topic_tweets:
                print_tweet(topic_tweets.pop())
            else:
                return

def main(args):
    parser = optparse.OptionParser("""Usage: %prog [-s <search term> | -t | -u <username>]""")

    parser.add_option("-s", "--search",
                      type="string",
                      action="store",
                      dest="search_term",
                      default=None,
                      help="Display tweets containing a particular string.")
    parser.add_option("-t", "--trending-topics",
                      action="store_true",
                      dest="trending_topics",
                      default=False,
                      help="Display the trending topics.")
    parser.add_option("-u", "--user",
                      type="string",
                      action="store",
                      dest="username",
                      default=None,
                      help="Display tweets for a particular public user.")
    parser.add_option("-w", "--trending-tweets",
                      action="store_true",
                      dest="trending_tweets",
                      default=None,
                      help="Display the tweets from trending topics.")

    (opts, args) = parser.parse_args(args)

    if opts.search_term:
        search(opts.search_term)
    elif opts.trending_topics:
        trending_topics()
    elif opts.username:
        user_tweets(opts.username)
    elif opts.trending_tweets:
        trending_tweets()

if __name__ == "__main__":
    main(sys.argv[1:])
  

PS:有时会遇到程序报错,缺少module,可能系统安装过python-twitter,但是版本较低,因此可以首先卸载twitter-python 再重新安装,卸载命令为:pip uninstall python-twitter。

2.tweepy:

首先tweepy下载:https://github.com/tweepy/tweepy

时间: 2024-08-06 07:57:16

Twitter search API的相关文章

ElasticSearch Search API简介

REST request URI curl 'localhost:9200/bank/_search?q=*&pretty' 1. localhost:9200/bank/_search,以 _search 结尾,标明我们是调用 Search API 来执行查询操作. 2. 查询条件以 URI 的参数形式给出. 3. q=* 参数让 ElasticSearch 匹配所有的文档. 4. pretty 参数标明让结果返回对人友好的 JSON 格式. REST request body curl -X

申请Bing Search API

地址:https://datamarket.azure.com/home 没有帐号先注册一个,然后登录. 1:在数据中订阅Bing Search API,如果找不到就使用这个地址: https://datamarket.azure.com/browse?publisher=f8ede0df-591f-4722-b646-e5eb86f0ae52&price=any 2:打开后 右侧选择要注册的类型,有免费和收费选择,点注册: 如果显示 在你的市场中未提供   则把用户信息中的语言 地区神马的改成

Sample-Code:Bing Search API

Demo link: http://code.msdn.microsoft.com/windowsazure/How-to-use-bing-search-API-4c8b287e Aspx Code: <form id="form1" runat="server"> <div> <asp:TextBox ID="tbQueryString" runat="server" Height="

设计Twitter的api

355. Design Twitter 题意:设计Twitter的API,实现以下功能. postTweet(userId, tweetId): Compose a new tweet. getNewsFeed(userId): Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed

Elasticsearch学习笔记(二)Search API 与 Query DSL

一. Search API eg: GET /mall/product/_search?q=name:productName&sort=price desc 特点:search的请求参数都是以HTTP请求的的query stirng 附带的 适用范围:适用于临时的在命令行使用一些工具,比如curl,快速的发出请求,来检索想要的信息: 适用于简单的查询条件 二.Query DSL 将Query DSL视为ASL查询则有两种类型的查询语句: 叶子查询语句(Leaf Query clause) : 叶

ElasticSearch search api的基础语法+Query DSL搜索+filter与query对比+组合查询+定位不合法的搜索

一. search api的基础语法 1.search语法 GET /search{} GET /index1,index2/type1,type2/search{} GET /_search{ "from": 0, "size": 10} 2.http协议中get是否可以带上request body HTTP协议,一般不允许get请求带上request body,但是因为get更加适合描述查询数据的操作,因此还是这么用了 GET /_search?from=0&a

set up custom search api

sign up google developer console, create project, generate API key http://stackoverflow.com/questions/4082966/google-web-search-api-deprecated-what-now/11206266#11206266 Example Code: cx is custom search engine key, developer key is api key ""&q

Elasticsearch Search API

当执行一个搜索时,它将这个搜索请求广播给所有的索引分片.可以通过提供路由参数来控制要搜索哪些分片.例如,当检索tweets这个索引时,路由参数可以设置为用户名: curl -X POST "localhost:9200/twitter/_search?routing=kimchy" -H 'Content-Type: application/json' -d' { "query": { "bool" : { "must" :

iOS9 Search API 之 Spotlight

iOS9以后 有三种api提供搜搜方式 加强引导用户关注 我们的app及相关内容的方式 NSUserActivity Web Markup  Core Spotlight 用法 前两种 实战操作性不够强(后续补充) 这里先讲 spotlight 实现机制和方法 分析 iOS 8的时候 spotlight 就可以搜索应用名称,iOS9以后,加强了深度搜索功能,就是 你预设置在手机里的”埋点”,都可以在搜索里面,展示给用户,当用户点击暴露的搜索结果时候 会根据需求进行唤醒应用/跳转指定页面等操作.