How to specify browser language in Puppeteer

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-30 01:26:59

问题


I would like to launch a Google Chrome browser with language Spanish es using Puppeteer.

I've tried puppeteer.launch(args:['--lang=es',...],...) but it didn't work.

I've tried passing the environment variable LANGUAGE=es mocha puppeteer-test.js but it didn't work.

I've tried using the userDataDir option and passing a folder with a Preferences file a { "intl": { "accept_languages": "es" } } but the browser Settings - Languages still don't show Spanish and neither does window.navigator.languages neither window.navigator.language

I'm using
Puppeteer 0.11.0
Node 8.4.0
NPM 5.2.0
macOS El Capitan 10.11.6
MacBook Pro Retina, 15-inch, Mid 2015


回答1:


There are several ways to change locale, you can try all of them to find what works for you,

Use Args when launching

const browser = await puppeteer.launch({
    headless: false,
    args: ['--lang=bn-BD,bn']
});

Send the language as Header

await page.setExtraHTTPHeaders({
    'Accept-Language': 'bn'
});

Forcefully set the language

// Set the language forcefully on javascript
await page.evaluateOnNewDocument(() => {
    Object.defineProperty(navigator, "language", {
        get: function() {
            return ["bn-BD"];
        }
    });
    Object.defineProperty(navigator, "languages", {
        get: function() {
            return ["bn-BD", "bn"];
        }
    });
});

For the sake of testing, I'll test this in multiple languages, including es, and here is the result.

Google search:

BrowserLeaks:




回答2:


There's an error in Md-Abu-Taher's answer.

The response to navigator.language should return a string, not an array. Try it in your own browser console.

The code snippet should be:

await page.evaluateOnNewDocument(() => {
    Object.defineProperty(navigator, "language", {
        get: function() {
            return "en-GB";
        }
    });
    Object.defineProperty(navigator, "languages", {
        get: function() {
            return ["en-GB", "en"];
        }
    });
});


来源:https://stackoverflow.com/questions/46908636/how-to-specify-browser-language-in-puppeteer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!