DEV Community

Cover image for Practical Puppeteer: Playing with Google Translate to translate a text
Sony AK
Sony AK

Posted on • Updated on

Practical Puppeteer: Playing with Google Translate to translate a text

Today we will play with Puppeteer to control Google Translate service. The scenario is to translate a text from Bahasa Indonesia to English. Language code for Bahasa Indonesia is id and language code for English is en.

You can adjust the language code with your own.

Technically speaking, I just want to control this URL.



https://translate.google.com/#view=home&op=translate&sl=id&tl=en


Enter fullscreen mode Exit fullscreen mode

sl parameter is language code for source text
tl parameter is language code for translated text

Let's play.

Preparation

Install Puppeteer



npm i puppeteer


Enter fullscreen mode Exit fullscreen mode

Sample code

File google_translate.js



const puppeteer = require('puppeteer');

(async () => {
    let launchOptions = { headless: false, args: ['--start-maximized'] };

    const browser = await puppeteer.launch(launchOptions);
    const page = await browser.newPage();

    // set viewport and user agent (just in case for nice viewing)
    await page.setViewport({width: 1366, height: 768});
    await page.setUserAgent('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36');

    // define source and target language code
    let sourceLang = 'id', targetLang = 'en';

    await page.goto(`https://translate.google.com/#view=home&op=translate&sl=${sourceLang}&tl=${targetLang}`);

    // detect the source textarea for input data (source string)
    await page.waitForSelector('#source');
    await page.waitFor(1000);

    // string that we want to translate and type it on the textarea
    let sourceString = 'Apa kamu sadar kalau muka kamu itu jelek sekali?';
    await page.type('#source', sourceString);

    // wait for the result container available
    await page.waitForSelector('.result-shield-container');
    await page.waitFor(3000);

    // get the result string (translated text)
    const translatedResult = await page.evaluate(() => {
        return document.querySelectorAll('.result-shield-container')[0].textContent;
    });

    // display the source and translated text to console
    console.log(`${sourceLang}: ${sourceString}\n${targetLang}: ${translatedResult}`);

    await page.waitFor(1000);
    await browser.close();
})();


Enter fullscreen mode Exit fullscreen mode

The code are self explanatory. I set the headless option to false, so we can see the browser automation in action.

Run it



node google_translate.js


Enter fullscreen mode Exit fullscreen mode

Sample of result are below

Alt Text

Ow nice.

I hope you enjoy it. Thank you very much.

Repository of this sample is available at https://github.com/sonyarianto/translate-text-with-google-translate-and-puppeteer

Reference

Top comments (0)