Twitter API在Python中进行游说

时间:2013-02-18 15:48:09

标签: python twitter

这里是一个python初学者,试图让Twitter cursoring在我的脚本中工作,这样我就可以迭代属于Twitter上列表的所有用户。这里很简单的逻辑。从此API请求开始:

https://api.twitter.com/1/lists/members.json?slug=all-fox-news&owner_screen_name=foxnews&cursor=-1

然后有一个for循环将cursor = -1改为next_cursor_str在解析的JSON中的任何内容。但是,我很难将next_cursor_str存储为字符串。有没有人有这方面的经验?下面是我的代码,工作正常,只是没有游标循环:

import urllib2
import json
import csv
from time import sleep

outfile_path='Out.csv'
writer = csv.writer(open(outfile_path, 'w'))
headers = ['users']
writer.writerow(headers)

url = urllib2.Request('https://api.twitter.com/1/lists/members.json?slug=all-fox-news&owner_screen_name=foxnews&cursor=-1')
parsed_json = json.load(urllib2.urlopen(url))
print parsed_json
for tweet in parsed_json['users']:
    row = []
    row.append(str(tweet['screen_name'].encode('utf-8')))
    writer.writerow(row)
sleep(5)

根据以下答案,parsed_json [“next_cursor_str”]正是我所需要的。我认为这里的while循环会很好,但它却无法在0结束:

n = parsed_json["next_cursor_str"]
int(n)
while n is not 0:
    url = urllib2.Request('https://api.twitter.com/1/lists/members.json?slug=all-fox-news&owner_screen_name=foxnews&cursor=' + str(n))
    parsed_json = json.load(urllib2.urlopen(url))
    print parsed_json
    for tweet in parsed_json['users']:
        row = []
        row.append(str(tweet['screen_name'].encode('utf-8')))
        writer.writerow(row)
    n = parsed_json["next_cursor_str"]

1 个答案:

答案 0 :(得分:2)

next_cursor_str只是存储在您的parsed_json变量中:

print parsed_json["next_cursor_str"]
# 1395095221152647652