如何使用Selenium WebDriver自动化Salesforce登录OTP功能(已尝试Cookie方法)
Hey there! Let's figure out how to automate Salesforce OTP login with Selenium—since loading cookies didn't work for you, let's walk through some more reliable methods that should solve this.
This approach bypasses the OTP UI flow entirely by using Salesforce's OAuth password grant to get a valid session ID, then injecting that session into Selenium. It's way more stable than cookie-based methods because Salesforce sessions are designed to work with this API.
Steps & Code Example:
First, set up a Connected App in Salesforce:
- Go to Setup > Apps > App Manager > New Connected App
- Enable the "Password Flow" under OAuth settings, and note down your
Client IDandClient Secret - Make sure your user has a security token (you can reset it from your Salesforce profile if needed)
Use the API to get a session ID, then inject it into Selenium:
import requests from selenium import webdriver # Replace these with your actual credentials username = "your-salesforce-username" password = "your-password+your-security-token" # Combine password and security token client_id = "your-connected-app-client-id" client_secret = "your-connected-app-client-secret" instance_url = "https://your-domain.my.salesforce.com" # Step 1: Fetch session ID via Salesforce OAuth API token_endpoint = f"{instance_url}/services/oauth2/token" payload = { "grant_type": "password", "client_id": client_id, "client_secret": client_secret, "username": username, "password": password } response = requests.post(token_endpoint, data=payload) session_id = response.json()["access_token"] # Step 2: Inject session into Selenium driver = webdriver.Chrome() driver.get(instance_url) # Add the critical "sid" cookie (this is your authenticated session) driver.add_cookie({ "name": "sid", "value": session_id, "domain": ".salesforce.com", "path": "/" }) # Refresh to load the authenticated session driver.refresh()
If you absolutely need to simulate the full manual login UI, you can generate or retrieve the OTP programmatically:
Subcase A: Using TOTP Authenticator Apps (e.g., Google Authenticator)
Salesforce uses the TOTP algorithm for authenticator app OTPs. You just need the secret key from your Salesforce OTP setup (you can find this in Salesforce's Security Settings under "Authenticator App" > "View Secret Key").
import pyotp from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # Replace with your details username = "your-username" password = "your-password" totp_secret = "your-salesforce-totp-secret" # Initialize driver driver = webdriver.Chrome() driver.get("https://login.salesforce.com") # Enter username/password and submit driver.find_element(By.ID, "username").send_keys(username) driver.find_element(By.ID, "password").send_keys(password) driver.find_element(By.ID, "Login").click() # Wait for OTP field to load otp_input = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "otp")) ) # Generate valid OTP totp = pyotp.TOTP(totp_secret) current_otp = totp.now() # Enter OTP and submit otp_input.send_keys(current_otp) driver.find_element(By.ID, "save").click() # Adjust button ID if needed
Subcase B: Reading OTP from Email/SMS
If OTPs are sent to your email or phone, you can use libraries like imaplib (for email) or SMS APIs (like Twilio) to fetch the OTP and input it into Selenium. Just note that this requires access to your email/SMS inbox programmatically.
For quick local testing, you can reuse your existing Chrome profile where you've already logged into Salesforce (and saved the OTP session). This skips OTP prompts because the browser remembers your authenticated session.
from selenium import webdriver from selenium.webdriver.chrome.options import Options chrome_options = Options() # Replace with your Chrome user data path # Windows example: r"C:\Users\YourName\AppData\Local\Google\Chrome\User Data" # Mac example: "~/Library/Application Support/Google/Chrome" chrome_options.add_argument(r"user-data-dir=path-to-your-chrome-user-data") chrome_options.add_argument("--profile-directory=Default") # Use your default profile driver = webdriver.Chrome(options=chrome_options) driver.get("https://login.salesforce.com") # You should be logged in automatically if your profile has an active session
Quick Notes:
- 方案1 is the best choice for CI/CD pipelines or long-term automation because it's not dependent on UI changes or OTP delivery.
- 方案2 works if you need to test the full login flow, but requires access to the TOTP secret or inbox.
- 方案3 is great for local debugging, but won't work in headless/CI environments where you can't reuse a local profile.
内容的提问来源于stack exchange,提问作者Senthil

