Python中使用Twitter API进行游标处理
我是一名Python初学者,正在尝试在我的脚本中实现Twitter的游标功能,这样我就可以遍历属于某个列表的所有用户。这个逻辑其实很简单。首先,我需要发出一个API请求:
https://api.twitter.com/1/lists/members.json?slug=all-fox-news&owner_screen_name=foxnews&cursor=-1
接着,我想用一个for循环把游标从-1改成解析后的JSON中的next_cursor_str。不过,我在把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 个回答
2
next_cursor_str
就是简单地存储在你的 parsed_json
变量里:
print parsed_json["next_cursor_str"]
# 1395095221152647652