问题
I'm trying to get my remote chrome driver to request pages in German instead of English. Following the chromedriver documentation and list of chrome preferences, I tried to set it like this:
capabilities.setCapability(ChromeOptions.CAPABILITY, getChromeOptions());
Map<String, String> chromePrefs = new HashMap<String,String>();
chromePrefs.put("settings.language.preferred_languages", "de-DE,de");
capabilities.setCapability("chrome.prefs", chromePrefs);
And I can see it reaches chromedriver from the log file:
[0.453][FINE]: Initializing session with capabilities {
"browserName": "chrome",
"chrome.prefs": {
"settings.language.preferred_languages": "de-DE,de"
},
"chromeOptions": {
"args": [ "--ignore-certificate-errors" ],
"extensions": [ ]
},
"platform": "ANY",
"version": null
}
But it still requests english pages and this can also be seen by opening the content settings in the preferences. What am I doing wrong?
回答1:
(Edit) Long story short:
intl.accept_languagesis the preferences key to manipulate what languages are requested for a page.Set the capability for the preferences using the (newer and preferred)
ChromeOptionsmechanism (otherwise it won't work if any ChromeOptions are set by you or your language bindings, see Issues 104 & 95).ChromeOptions support for setting preferences is not completely implemented yet. So, unfortunately, you have to use the dirty workaround from my comment 6 to Issue 95
An alternative might be to create a user profile with the desired language settings and use ChromeOption to set the (command line) option to use this profile, as mentioned on the chromedriver capabilities wiki page.
回答2:
Pyhon examples
Note: I test it with "en,en_US" accepted language, but I don't see why it wouldn't work with de_DE as long as locale is available on the system.
This work with selenium
from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options
from splinter.driver.webdriver import BaseWebDriver, WebDriverElement
options = Options()
options.add_experimental_option('prefs', {'intl.accept_languages': 'de_DE'})
browser = BaseWebDriver()
browser.driver = Chrome(chrome_options=options)
browser.visit('http://example.com')
With splinter there is 2 options :
Splinter API only
from splinter import Browser
from splinter.driver.webdriver.chrome import Options
options = Options()
options.add_experimental_option('prefs', {'intl.accept_languages': 'de_DE'})
browser = Browser('chrome', options=options)
browser.visit('http://example.com')
Splinter and selenium API
from splinter import Browser
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_experimental_option('prefs', {'intl.accept_languages': 'de_DE'})
browser = Browser('chrome', options=options)
browser.visit('http://example.com')
来源:https://stackoverflow.com/questions/11289597/webdriver-how-to-specify-preferred-languages-for-chrome