获取自动生成的Spotify账号Bearer Token的方法及Selenium查看请求头的实现
Getting the Bearer Token
The signup endpoint you’re using doesn’t return a Bearer Token directly—you need to authenticate the newly created account via Spotify’s token endpoint after a successful signup. Here’s how to implement this:
Step 1: Verify Signup Success
First, check if your signup request succeeded by parsing the JSON response. Spotify’s signup endpoint typically includes a status field to indicate success (adjust this check based on the actual response structure you receive):
signup_response = resp.json() if signup_response.get("status") == 1: # Example success condition # Proceed to fetch the token else: print(f"Signup failed: {signup_response.get('error')}")
Step 2: Request the Bearer Token
Use Spotify’s password grant flow to fetch the user-level access token. You’ll use the same public client ID from your signup request (a1e486e2729f46d6bb368d6b2bcda326):
import requests import base64 def get_bearer_token(email, password): client_id = "a1e486e2729f46d6bb368d6b2bcda326" client_secret = "" # Spotify's public web client has no secret # Encode client ID/secret for Basic authentication auth_str = f"{client_id}:{client_secret}" b64_auth = base64.b64encode(auth_str.encode()).decode() token_url = "https://accounts.spotify.com/api/token" payload = { "grant_type": "password", "username": email, "password": password, "client_id": client_id } headers = { "Authorization": f"Basic {b64_auth}", "Content-Type": "application/x-www-form-urlencoded" } token_resp = requests.post(token_url, data=payload, headers=headers) if token_resp.status_code == 200: return token_resp.json().get("access_token") else: print(f"Token request failed: {token_resp.text}") return None
Step 3: Integrate into Your Generator
Call this token-fetching function right after a successful signup to capture the Bearer Token:
def gen(): global accs, invalid, password currentuserfull = email() username = name() # Your existing signup request code here... signup_response = resp.json() if signup_response.get("status") == 1: bearer_token = get_bearer_token(currentuserfull, password) if bearer_token: accs.append({ "email": currentuserfull, "password": password, "token": bearer_token }) else: invalid += 1 else: invalid +=1
Note: Spotify has deprecated the password grant flow for most third-party apps, but it may still work with their public web client ID. If this fails, you’ll need to explore more complex flows like the authorization code flow (though it’s less suited for automation).
Viewing Request Headers with Selenium
Selenium 4+ supports the Chrome DevTools Protocol (CDP) to capture network requests and their headers. Here’s a working example to log all requests during signup:
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import json def capture_spotify_request_headers(): # Initialize Chrome with DevTools enabled options = webdriver.ChromeOptions() options.add_argument("--start-maximized") driver = webdriver.Chrome(service=Service(), options=options) # Enable network monitoring via CDP driver.execute_cdp_cmd("Network.enable", {}) # Store captured request data captured_requests = [] # Callback to log every outgoing request def log_request(event): req = event["params"]["request"] captured_requests.append({ "url": req["url"], "headers": req["headers"] }) print(f"\nRequest URL: {req['url']}") print("Headers:") for key, value in req["headers"].items(): print(f" {key}: {value}") # Attach the callback to request events driver.execute_cdp_cmd("Network.requestWillBeSent", {}, log_request) # Navigate to Spotify's signup page driver.get("https://www.spotify.com/uk/signup") # Fill out the signup form (adjust selectors to match the current page) wait = WebDriverWait(driver, 10) # Example: Fill email and password fields email_input = wait.until(EC.presence_of_element_located((By.ID, "email"))) email_input.send_keys("your_generated_email@example.com") password_input = wait.until(EC.presence_of_element_located((By.ID, "password"))) password_input.send_keys("your_password") # Fill other required fields (birthdate, agree to terms, etc.) # ... # Submit the form submit_btn = wait.until(EC.element_to_be_clickable((By.XPATH, "//button[@type='submit']"))) submit_btn.click() # Wait for requests to complete driver.implicitly_wait(5) # Save captured data to a file for later review with open("spotify_signup_requests.json", "w") as f: json.dump(captured_requests, f, indent=2) driver.quit() return captured_requests
This script will log all network requests made during the signup process, including the exact headers sent by the browser. You can filter through the captured data to find the signup request’s headers specifically.
内容的提问来源于stack exchange,提问作者jack12




