当前位置: 首页 > 知识库问答 >
问题:

如何使用Python检索给定用户的所有Tweet和属性?

曾山
2023-03-14

我正在尝试从Twitter检索数据,使用Tweepy作为在命令行中键入的用户名。我想提取相当多关于状态和用户的数据,所以想出了以下内容:

请注意,我正在导入所有必需的模块,并且具有oauth键(只是此处未包含)并且文件名正确,刚刚更改:

# define user to get tweets for. accepts input from user
user = tweepy.api.get_user(input("Please enter the twitter username: "))

# Display basic details for twitter user name
print (" ")
print ("Basic information for", user.name)
print ("Screen Name:", user.screen_name)
print ("Name: ", user.name)
print ("Twitter Unique ID: ", user.id)
print ("Account created at: ", user.created_at)

timeline = api.user_timeline(screen_name=user, include_rts=True, count=100)
    for tweet in timeline:
        print ("ID:", tweet.id)
        print ("User ID:", tweet.user.id)
        print ("Text:", tweet.text)
        print ("Created:", tweet.created_at)
        print ("Geo:", tweet.geo)
        print ("Contributors:", tweet.contributors)
        print ("Coordinates:", tweet.coordinates) 
        print ("Favorited:", tweet.favorited)
        print ("In reply to screen name:", tweet.in_reply_to_screen_name)
        print ("In reply to status ID:", tweet.in_reply_to_status_id)
        print ("In reply to status ID str:", tweet.in_reply_to_status_id_str)
        print ("In reply to user ID:", tweet.in_reply_to_user_id)
        print ("In reply to user ID str:", tweet.in_reply_to_user_id_str)
        print ("Place:", tweet.place)
        print ("Retweeted:", tweet.retweeted)
        print ("Retweet count:", tweet.retweet_count)
        print ("Source:", tweet.source)
        print ("Truncated:", tweet.truncated)

我希望最终遍历用户的所有推文(最多3200条限制)。不过,首先要做的是。到目前为止,尽管我有两个问题,但我收到了以下关于转发的错误消息:

Please enter the twitter username: barackobamaTraceback (most recent call last):
  File " usertimeline.py", line 64, in <module>
    timeline = api.user_timeline(screen_name=user, count=100, page=1)
  File "C:\Python32\lib\site-packages\tweepy-1.4-py3.2.egg\tweepy\binder.py", line 153, in _call
    raise TweepError(error_msg)
tweepy.error.TweepError: Twitter error response: status code = 401
Traceback (most recent call last):
  File "usertimeline.py", line 42, in <module>
    user = tweepy.api.get_user(input("Please enter the twitter username: "))
  File "C:\Python32\lib\site-packages\tweepy-1.4-py3.2.egg\tweepy\binder.py", line 153, in _call
    raise TweepError(error_msg)
tweepy.error.TweepError: Twitter error response: status code = 404

将用户名作为变量传递似乎也是一个问题:

Traceback (most recent call last):
  File " usertimleline.py", line 64, in <module>
    timeline = api.user_timeline(screen_name=user, count=100, page=1)
  File "C:\Python32\lib\site-packages\tweepy-1.4-py3.2.egg\tweepy\binder.py", line 153, in _call
    raise TweepError(error_msg)
tweepy.error.TweepError: Twitter error response: status code = 401

我已经隔离了这两个错误,即它们没有一起工作。

原谅我的无知,我对推特应用程序接口不太感兴趣,但我学得很快。Tweepy留档真的很糟糕,我已经在网上阅读了很多,只是似乎无法修复这个问题。如果我能解决这个问题,我会留档。

我知道如何在提取后将数据传输到 MySQL 数据库(它会这样做,而不是打印到屏幕上)并对其进行操作,以便我可以用它做一些事情,它只是把它拿出来我遇到了问题。有没有人有任何想法,或者我应该考虑另一种方法?

非常感谢任何帮助。干杯

编辑:

根据埃里克·奥尔森今天早上的建议;我做了以下事情。

1) 创建了一套全新的Oauth证书进行测试。2) 将代码复制到新脚本,如下所示:

认证

consumer_key = "(removed)"
consumer_secret = "(removed)"
access_key="88394805-(removed)"
access_secret="(removed)"
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api=tweepy.API(auth)



# confirm account being used for OAuth
print ("API NAME IS: ", api.me().name)
api.update_status("Using Tweepy from the command line")

我第一次运行脚本时,它工作正常并更新我的状态并返回 API 名称,如下所示:

>>> 
API NAME IS:  Chris Howden

然后从那一刻起,我得到这个:

Traceback (most recent call last):
  File "C:/Users/Chris/Dropbox/Uni_2012-3/6CC995 - Independent Studies/Scripts/get Api name and update status.py", line 19, in <module>
    api.update_status("Using Tweepy frm the command line")
  File "C:\Python32\lib\site-packages\tweepy-1.4-py3.2.egg\tweepy\binder.py", line 153, in _call
    raise TweepError(error_msg)
tweepy.error.TweepError: Twitter error response: status code = 403

我能看到它做这样的事情的唯一原因是它拒绝了生成的访问令牌。我不需要续订访问令牌,是吗?

共有2个答案

国胤
2023-03-14

您得到401响应,这意味着“未经授权”。(请参阅HTTP状态代码)

你的代码看起来不错。使用<code>api。user_timeline(screen_name=“some_screen_name”)适用于我的旧示例。

我猜你要么需要授权这个应用,要么你的OAuth设置有问题。

也许你已经发现了这一点,但下面是我开始的简短代码示例:https://github.com/nloadholtes/tweepy/blob/nloadholtes-examples/examples/oauth.py

邢凌
2023-03-14

如果你愿意尝试另一个库,你可以给rauth一个机会。已经有一个Twitter的例子,但是如果你觉得懒,只是想要一个工作的例子,这里是我如何修改演示脚本:

from rauth import OAuth1Service

# Get a real consumer key & secret from https://dev.twitter.com/apps/new
twitter = OAuth1Service(
    name='twitter',
    consumer_key='J8MoJG4bQ9gcmGh8H7XhMg',
    consumer_secret='7WAscbSy65GmiVOvMU5EBYn5z80fhQkcFWSLMJJu4',
    request_token_url='https://api.twitter.com/oauth/request_token',
    access_token_url='https://api.twitter.com/oauth/access_token',
    authorize_url='https://api.twitter.com/oauth/authorize',
    base_url='https://api.twitter.com/1/')

request_token, request_token_secret = twitter.get_request_token()

authorize_url = twitter.get_authorize_url(request_token)

print 'Visit this URL in your browser: ' + authorize_url
pin = raw_input('Enter PIN from browser: ')

session = twitter.get_auth_session(request_token,
                                   request_token_secret,
                                   method='POST',
                                   data={'oauth_verifier': pin})

params = {'screen_name': 'github',  # User to pull Tweets from
          'include_rts': 1,         # Include retweets
          'count': 10}              # 10 tweets

r = session.get('statuses/user_timeline.json', params=params)

for i, tweet in enumerate(r.json(), 1):
    handle = tweet['user']['screen_name'].encode('utf-8')
    text = tweet['text'].encode('utf-8')
    print '{0}. @{1} - {2}'.format(i, handle, text)

您可以按原样运行,但请务必更新凭据!这些仅用于演示目的。

完全披露,我是rauth的维护者。

 类似资料:
  • 问题内容: 在Unix / Linux中,如何通过命令行找出给定用户所在的组? 问题答案: 要么

  • 当我在AEM上使用下面的查询QueryDebug 以及形成的URL/JSON QueryBuilder链接。 我可以看到每个资产的所有属性,包括jcr:内容,元数据如下: 我需要将相同的结果返回到服务/endpoint,我正在为客户构建AEM。当我将上述查询转换为查询生成器API时 如何检索所有值? 如果我使用,我们只能看到下的属性,而不能看到其他属性。 和 如果我使用

  • 假设一个本体中有几个类定义: 如何检索给定类的所有功能。在上面的示例中,对于给定的类A,应该返回CapabilityB和CapabilityC。

  • 我将一些数据存储为neo4j节点。此节点具有一些关联的C#类未描述的属性,因此在neo4jclient查询返回时不会自动映射回该类。 例如,这个C类: 存储在neo4j中,然后使用以下neo4jclient fluent代码检索: 将用名称和编号填充Node对象,但保留对CustomClass对象的空引用。 为了解决这个问题,我将CustomClass序列化为JSON字符串,并将其作为字符串属性存

  • 我正试图从一个站点获取一个数字(比特币的价值),使用下面的代码 它应该打印一个数字,但它没有打印。我尝试使用其他模块,如.gettext,但结果总是没有。我可以用什么来获得我想要的值?

  • 问题内容: 如何获取用@ decorator2装饰的给定类A的所有方法? 问题答案: 方法1:基本注册装饰器 我已经在这里回答了这个问题:在Python中通过数组索引调用函数=) 方法2:源代码解析 如果您无法控制 类 定义,而 _ 类 _定义 是您想假设的一种解释,则这是 不可能的 (没有代码的读取- 反射),因为装饰器可以是无操作的装饰器(例如在我的链接示例中)仅返回未修改的函数。(但是,如果