You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Twitter API按点赞时间排序收藏推文?解决增量下载问题

Solution for Incremental Download of Twitter Liked Media (Sorted by Favorite Time)

Great question—this is such a frustrating limitation of Twitter's v1.1 Favorites API, since it only returns tweets sorted by their creation time, not the timestamp when you actually favorited them. The good news is there's an official fix with Twitter API v2, which addresses exactly this issue. Let's walk through your options:

Twitter's newer API v2 explicitly supports sorting liked tweets by the time you favorited them. The /users/{id}/liked_tweets endpoint lets you use the sort_order=recency parameter, which returns your most recently liked tweets first—matching the behavior you see on the Twitter web interface.

How to implement this with Tweepy:

  • First, upgrade Tweepy to the latest version (it fully supports API v2):
    pip install --upgrade tweepy
    
  • Use the Client class instead of the v1.1 API object. Here's a quick snippet to get started:
    import tweepy
    
    # Initialize v2 client with your API keys/tokens
    client = tweepy.Client(
        bearer_token="YOUR_BEARER_TOKEN",
        consumer_key="YOUR_CONSUMER_KEY",
        consumer_secret="YOUR_CONSUMER_SECRET",
        access_token="YOUR_ACCESS_TOKEN",
        access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
    )
    
    # Get your user ID (you can hardcode this after the first run)
    user = client.get_user(username="YOUR_USERNAME")
    user_id = user.data.id
    
    # Fetch liked tweets sorted by recency (most recent likes first)
    # Use pagination to get all new likes since your last download
    pagination_token = None
    # Load your saved pagination token from a file/database (if exists)
    # with open("last_pagination_token.txt", "r") as f:
    #     pagination_token = f.read().strip()
    
    while True:
        response = client.get_liked_tweets(
            user_id,
            max_results=100,  # Max per request
            sort_order="recency",
            pagination_token=pagination_token,
            expansions=["attachments.media_keys"],
            media_fields=["url", "type"]
        )
    
        # Process each tweet's media
        for tweet in response.data:
            if "attachments" in tweet.data:
                media_keys = tweet.data["attachments"]["media_keys"]
                for media in response.includes["media"]:
                    if media.media_key in media_keys:
                        if media.type in ["photo", "video", "gif"]:
                            # Download the media here (use media.url for photos, or get video variants)
                            print(f"Downloading media: {media.url}")
    
        # Update pagination token for next run
        pagination_token = response.meta.get("next_token")
        if not pagination_token:
            break
    
    # Save the last pagination token to resume next time
    with open("last_pagination_token.txt", "w") as f:
        f.write(pagination_token or "")
    

Key benefits:

  • No more wasting time scrolling through old tweets to find newly favorited content
  • Official, stable API support (no risk of breaking from web UI changes)
  • Works seamlessly with incremental downloads using the pagination_token to pick up where you left off

Since you're familiar with Java and JavaScript, you can implement this in those languages too:

  • Java: Use the Twitter4J v2 library (look for methods related to liked tweets)
  • JavaScript: Use the twitter-api-v2 npm package, which supports the v2 liked tweets endpoint with sortOrder: 'recency'

2. Local ID Tracking (Fallback for API v1.1)

If you can't switch to v2 right now, you can maintain a local database/text file of all tweet IDs you've already downloaded. Each time you run the script:

  • Fetch all your favorites (in batches using Tweepy's api.favorites() with count and max_id parameters)
  • Compare each tweet's ID against your local list
  • Download media only for IDs that aren't already in the list
  • Update the local list with new IDs

This works, but it's inefficient if you have a large number of favorites—you'll have to fetch all your favorites every time, even if only a few are new.

3. Selenium Web Scraping (Last Resort)

If neither API option works for you, simulating the web UI with Selenium is a valid fallback. Since the Twitter web interface shows likes sorted by the time you favorited them, you can:

  • Automate logging into your Twitter account
  • Navigate to your likes page
  • Scroll to load new content
  • Extract media URLs from each tweet
  • Download the media

Just keep in mind that web scraping violates Twitter's Terms of Service if done at scale, and the UI can change at any time (breaking your script). It's slower and more fragile than using the API.


内容的提问来源于stack exchange,提问作者Eric Bromstead

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 14:32:45