简体   繁体   中英

how to get tweets using twitter API in python?

I'm a starter in python.I use the following code to get tweets depending on a input query.

import urllib
import urllib2
import json
def getData(keyword):
    url = 'http://search.twitter.com/search.json'
    data = {'q': keyword, 'lang': 'en', 'result_type': 'recent'}
    params = urllib.urlencode(data)
    try:
        req = urllib2.Request(url, params)
        response = urllib2.urlopen(req)
        jsonData = json.load(response)
        tweets = []
        for item in jsonData['results']:
            tweets.append(item['text'])
        return tweets
    except urllib2.URLError, e:
        self.handleError(e)
    return tweets
tweets = getData("messi")
print tweet

but i get the following error in the above code. Name Error: global name 'self' is not defined. How can i correct this error?

Like ChrisP said, first you need to remove self. from your code. then you might get another error as handleError function is not defined anywhere in your code. So, You have to define the handleError function as well if you have not defined it yet.

Take a look at the python doc to learn more about classes and objects.

import urllib
import urllib2
import json

#defining handleError
def handleError(e):
    #Error Handling code goes here

def getData(keyword):
    url = 'http://search.twitter.com/search.json'
    data = {'q': keyword, 'lang': 'en', 'result_type': 'recent'}
    params = urllib.urlencode(data)
    try:
        req = urllib2.Request(url, params)
        response = urllib2.urlopen(req)
        jsonData = json.load(response)
        tweets = []
        for item in jsonData['results']:
            tweets.append(item['text'])
        return tweets
    except urllib2.URLError, e:
        handleError(e) #removed self.
    return tweets
tweets = getData("messi")
print tweet

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM