I am trying to use twitter's API v1.1 and the urllib2 library to search for tweets containing certain keywords tweeted by a given user. The code I have tried is:
#!/usr/bin/python
import json
import sys
import urllib2
import os
#input twitter handle
handle = sys.argv[1]
sturl="https://api.twitter.com/1.1/search/tweets.json?q=immigrant%20OR%20illegal%20from%3A"+handle+"&src=typd";
url = urllib2.urlopen(sturl)
#convert the data and load it into json
data = json.load(url)
print len(data), "tweets"
This takes the desired user handle as the input and searches for tweets by this account containing the words "immigrant" or "illegal" and prints the number of such tweets. The error I get is:
File "tweet_search.py", line 16, in <module>
url = urllib2.urlopen(sturl)
File "/Users/David/anaconda/lib/python2.7/urllib2.py", line 154, in urlopen
return opener.open(url, data, timeout)
File "/Users/David/anaconda/lib/python2.7/urllib2.py", line 437, in open
response = meth(req, response)
File "/Users/David/anaconda/lib/python2.7/urllib2.py", line 550, in http_response
'http', request, response, code, msg, hdrs)
File "/Users/David/anaconda/lib/python2.7/urllib2.py", line 475, in error
return self._call_chain(*args)
File "/Users/David/anaconda/lib/python2.7/urllib2.py", line 409, in _call_chain
result = func(*args)
File "/Users/David/anaconda/lib/python2.7/urllib2.py", line 558, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 400: Bad Request
Am I using the query format incorrectly? I have tried browsing the API documentation and I can't find a query option to search by twitter handle as well as keyword.