Selenium自动化中如何修改Chrome浏览器语言?
Nice question! Testing your web app's automatic language switching based on browser settings is key to ensuring a solid international user experience. Let’s walk through the most reliable ways to set Chrome’s language in Selenium for this exact scenario.
Method 1: Use ChromeOptions with Experimental Preferences
This is the most consistent approach, as it directly sets Chrome’s internal language preferences. Here’s how to implement it in popular languages:
Python Implementation
First, import the required modules, then configure the language preference:
from selenium import webdriver from selenium.webdriver.chrome.options import Options # Initialize ChromeOptions chrome_options = Options() # Set language to French (use "zh-CN" for Simplified Chinese, "en-US" for American English, etc.) chrome_options.add_experimental_option( "prefs", {"intl.accept_languages": "fr,fr_FR"} ) # Launch Chrome with the configured options driver = webdriver.Chrome(options=chrome_options) # Navigate to your app and verify localization driver.get("your-app-url-here") # Add assertions to check if UI elements are in the target language
Java Implementation
For Java, the logic is similar—use ChromeOptions and a hashmap to set preferences:
import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import java.util.HashMap; import java.util.Map; public class LocalizationTest { public static void main(String[] args) { ChromeOptions options = new ChromeOptions(); Map<String, Object> prefs = new HashMap<>(); // Set language to Spanish prefs.put("intl.accept_languages", "es,es_ES"); options.setExperimentalOption("prefs", prefs); ChromeDriver driver = new ChromeDriver(options); driver.get("your-app-url-here"); // Validate that your app has switched to Spanish } }
Method 2: Command-Line Argument (Simpler Alternative)
If you prefer a more straightforward approach, you can pass the language as a command-line flag to Chrome:
# Python example for setting German language chrome_options.add_argument("--lang=de")
This works well for quick tests, but the experimental preferences method is often more reliable for maintaining the language setting across the entire browser session.
Important Tips
- Use the correct language code format:
language_code,language_code_REGION(e.g.,ja-JPfor Japanese,pt-BRfor Brazilian Portuguese). This ensures Chrome recognizes the full regional variant. - Always match your ChromeDriver version to your installed Chrome browser—mismatched versions can break experimental options.
- To confirm the language is set correctly, you can navigate to
chrome://settings/languagesin the driver instance, or directly check your app’s UI elements (e.g., assert that a "Submit" button is now "Envoyer" in French).
内容的提问来源于stack exchange,提问作者Vijendran Selvarajah

