python - Tweepy 使用 user_id(Python 脚本)从文本文件中关注 Twitter 用户

标签 python twitter tweepy

我正在尝试从一个包含 27 个 user_ids 的文本文件中跟踪 user_ids - 每行一个,例如:

217275660
234874181
27213931
230766319
83695362
234154065
68385750

我有一些代码似乎可以工作,除了它说 user_id 没有定义(见底部粘贴的错误)......但是 user_id 应该是 Tweepy 中的正确变量......之后有或没有 [,follow] .我的代码如下:

# Script to follow Twitter users from text file containing user IDs (one per line)

# Header stuff I've just thrown in from another script to authenticate

import json
import time
import tweepy
import pprint
from tweepy.parsers import RawParser
from auth import TwitterAuth
from datetime import datetime

auth = tweepy.OAuthHandler(TwitterAuth.consumer_key, TwitterAuth.consumer_secret)

auth.set_access_token(TwitterAuth.access_token, TwitterAuth.access_token_secret)

rawParser = RawParser()

api = tweepy.API(auth_handler = auth, parser = rawParser)

# Open to_follow.txt

to_follow = [line.strip() for line in open('to_follow.txt')]
print to_follow

# Follow everyone from list?!

for user_id in to_follow:
    try:
        api.create_friendship(user_id)
    except tweepy.TweepError as e:
        print e
        continue

print "Done."

错误是:

$ python follow.py
['217275660', '234874181', '27213931', '230766319', '83695362', '234154065', '68385750', '94981006', '215003131', '30921943', '234526708', '229259895', '88973663', '108144701', '233419650', '70622223', '95445695', '21756719', '229243314', '18162009', '224705840', '49731754', '19352387', '80815034', '17493612', '23825654', '102493081']
Traceback (most recent call last):
  File "follow.py", line 30, in <module>
    api.create_friendship(user_id)
NameError: name 'user_id' is not defined

最佳答案

确实 user_id 没有在您的代码中的任何地方定义。

我想你的意思是:
for user_id in to_follow:

user_id 在列表中

附带说明 - 下面的代码更好更正统:

with open('to_follow.txt') as f:
    for line in f:
        user_id = line.strip()
        api.create_friendship(user_id)

关于python - Tweepy 使用 user_id(Python 脚本)从文本文件中关注 Twitter 用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28548903/

相关文章:

python - 通过 Tweepy 获取 Twitter 中的所有关注者 ID

python - 将 SSL 验证与 Tweepy 结合使用

python - HOW TO : Use reindent. py for dummies

http - 通过 HTTPS 包含 Twitter Widgets.js

javascript - 在循环内使用 Q.allSettled 作为 promise 链

javascript - 如何在 Shiny 应用程序中嵌入 Twitter 时间线

python - 如何在 tweepy(python)中获取推文 ID(since_id、max_id)?

javascript - 更改 Django 中多条形图的颜色

python - Selenium 为数组(列表)中的每个项目创建多个 chrome 线程并同时执行函数

python - 使用 BeautifulSoup 或 golang colly 解析 HTML 时遇到问题