Twitter API with urllib2 in python
I want to use the Twitter API in Python to lookup user ids from name using the lookup method. I have done similar requests simply using
response = urllib2.urlopen('http://search.twitter.com...')
but for this one I need authentication. I don't think I can do it through the Google python twitter API because it doesn't have the lookup method. Any ideas how can开发者_Python百科 I can auth with urllib2??
You'd probably be better off using one of the actual Python libraries for the Twitter API:
http://dev.twitter.com/pages/libraries#python
Use urllib2.Request
to define the complete HTTP header:
request = urllib2.Request( 'http://twitter.com/...' )
request.add_header( 'Authorization', 'Basic ' + base64.b64encode( username + ':' + password ) )
response = urllib2.urlopen( request )
Note however that basic authorization will be disabled soon on twitter and you'll need to migrate to OAuth. Twitter API Wiki has some examples on that.
I'd recommend using the tweepy API.
https://github.com/tweepy/tweepy
Examples here: https://github.com/tweepy/tweepy/tree/master/examples
Using the Twython library, this is the code to lookup user IDs by name:
from twython import Twython
twitter = Twython(APP_KEY, APP_SECRET,OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
print twitter.show_user(screen_name=USER_NAME)["id"]
I hope this helps.
Authentication can be done with various of Twitter API wrapper libraries. A full list of wrapper API is listed in Twitter Developer Page.
Whatever the library is, you will have to implement OAuth authentication. This is sample code using Python Twitter Tool.
from twitter import *
MY_TWITTER_CREDS = os.path.expanduser('~/.my_app_credentials')
if not os.path.exists(MY_TWITTER_CREDS):
oauth_dance("My App Name", CONSUMER_KEY, CONSUMER_SECRET,
MY_TWITTER_CREDS)
oauth_token, oauth_secret = read_token_file(MY_TWITTER_CREDS)
twitter = Twitter(auth=OAuth(
oauth_token, oauth_secret, CONSUMER_KEY, CONSUMER_SECRET))
# Now search with Twitter
rel = t.search.tweets(q='whatever')['statuses']
# Now do whatever you want with rel object
精彩评论