使用pylast获取上周TOP3艺术家失败:返回None或报错求排查
Let’s walk through why you’re running into errors or getting None when trying to fetch your weekly top 3 artists with pylast, and how to fix these issues step by step:
1. First: Fill in Your Credentials Properly
Looking at your code, all credential fields (API_KEY, API_SECRET, username, and the password passed to pylast.md5()) are empty—this is almost certainly the root cause of your problems.
- Generate your own API key and secret via the Last.fm developer tools (you’ll need a Last.fm account for this).
- Replace the empty strings with your actual, valid credentials:
API_KEY = "your_real_api_key" API_SECRET = "your_real_api_secret" username = "your_lastfm_username" password_hash = pylast.md5("your_lastfm_password") - Double-check that the password hash is generated from your correct Last.fm password—typos here will break authentication silently.
2. Complete the Code to Fetch Top Artists
Your code cuts off after retrieving the authenticated user. You need to add the method call to actually pull the weekly top artists. Here’s a full, working example:
import pylast # Fill these in with your actual credentials API_KEY = "your_real_api_key" API_SECRET = "your_real_api_secret" username = "your_lastfm_username" password_hash = pylast.md5("your_lastfm_password") try: network = pylast.LastFMNetwork( api_key=API_KEY, api_secret=API_SECRET, username=username, password_hash=password_hash ) user = network.get_authenticated_user() # Fetch top 3 artists from the last 7 days top_artists = user.get_top_artists(period=pylast.PERIOD_7DAYS, limit=3) # Print the results print("Your weekly top 3 artists:") for rank, artist_entry in enumerate(top_artists, 1): print(f"{rank}. {artist_entry.item.get_name()} (total plays: {artist_entry.weight})") except pylast.WSError as e: print(f"Last.fm API Error: {e}") except Exception as e: print(f"Unexpected error: {e}")
3. Check for Common Edge Cases
- Private Account: If your Last.fm profile is set to private, the API won’t return your listening data. Head to your Last.fm settings and ensure your profile is public (or adjust API permissions if you need private access).
- No Recent Listens: If you haven’t scrobbled any tracks in the last 7 days,
top_artistswill be an empty list (notNone). Add a check for this:if not top_artists: print("No scrobbles found in the last 7 days.") - API Rate Limits: Last.fm enforces rate limits for API calls. If you’re making too many requests in a short time, you might get blocked temporarily. Add small delays between calls if you’re running multiple requests.
4. Debug with Error Handling
Adding try-except blocks (like in the example above) will catch specific pylast errors (invalid credentials, permission issues, etc.) and give you a clear message instead of silent failures or None returns. This is the fastest way to pinpoint exactly what’s going wrong.
内容的提问来源于stack exchange,提问作者Frenkieb

