簡體   English   中英

如何使用 twitter 搜索 API v2 和 Tweepy 獲取 python 中的所有推文(超過 100 條)和關聯的用戶字段?

[英]How to get all tweets (more than 100) and associated user fields in python using twitter search API v2 and Tweepy?

我正在嘗試使用 search_recent_tweets 獲取與特定查詢匹配的所有推文及其關聯的用戶字段(用戶名、姓名等)。 我嘗試使用分頁和展平,但它只會展平推文(而不是用戶字段)。 所以我正在嘗試在 get_user_tweets 中實現類似 next_token 的東西,但是 search_recent_tweets 沒有 pagination_next? 我怎樣才能做到這一點?

這是我要使用的代碼

import pandas as pd
import tweepy

BEARER_TOKEN = ''
api = tweepy.Client(BEARER_TOKEN)

response = api.search_recent_tweets(query = 'myquery',start_time = '2022-09-19T00:00:00Z', end_time = '2022-09-19T23:59:59Z',
                              expansions = ['author_id'],
                              tweet_fields = ['created_at'],
                              user_fields = ['username','name'],
                              max_results = 100)
tweet_df = pd.DataFrame(response.data)
metadata = response.meta
users = pd.concat({k: pd.DataFrame(v) for k, v in response.includes.items()}, axis=0)
users = users.reset_index(drop=True)
users.rename(columns={'id':'author_id'}, inplace=True)
all_tweets = tweet_df.merge(users)
next_token = metadata.get('next_token')
while next_token is not None:
    response = api.search_recent_tweets(query = 'myquery',start_time = '2022-09-19T00:00:00Z', end_time = '2022-09-19T23:59:59Z',
                            expansions = ['author_id'],
                            tweet_fields = ['created_at'],
                            user_fields = ['username','name'],
                            pagination_token=next_token,
                            max_results = 100)
    tweet_df = pd.DataFrame(response.data)
    metadata = response.meta
    users = pd.concat({k: pd.DataFrame(v) for k, v in response.includes.items()}, axis=0)
    users = users.reset_index(drop=True)
    users.rename(columns={'id':'author_id'}, inplace=True)
    tweets = tweet_df.merge(users)
    all_tweets.append(tweets)
    next_token = metadata.get('next_token')
    
all_tweets

您可以為此使用 GTdownloader:

from gtdownloader import TweetDownloader

# create downloader using Twitter API credentials
gtd = TweetDownloader(credentials='twitter_keys.yaml')

gtd.get_tweets('myquery', 
               lang='en', 
               max_tweets=100,
               start_time='09/19/2022', 
               end_time='09/20/2022'
               )

# accessing tweets data frame
gtd.tweets_df.head()

請參閱https://gtdownloader.readthedocs.io/上的文檔

編輯:免責聲明,我為我的研究編寫了這段代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM