-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
8145463
commit 484af3c
Showing
1 changed file
with
15 additions
and
13 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,20 +1,22 @@ | ||
#!/usr/bin/env node | ||
const { browser: { createBrowser } } = require('mega-scraper') | ||
const {browser: {createBrowser}} = require('mega-scraper') | ||
const args = require('yargs').argv | ||
async function translate ({ text, from = 'auto', to = 'en', browser, page } = {}) { | ||
if (!text) throw new Error('missing text') | ||
if (!from) throw new Error('missing from') | ||
if (!to) throw new Error('missing to') | ||
if (!browser) browser = await createBrowser({ headless: true, screenshot:true }) | ||
|
||
page = page || await browser.newPage() | ||
await page.goto(`https://translate.google.com/#view=home&op=translate&sl=${from}&tl=${to}&text=${encodeURIComponent(text)}`) | ||
await page.waitForSelector('[jsaction="copy:"] > div > div span > div > div > div > div > span', { timeout: 10000 }) | ||
async function translate({text, from = 'auto', to = 'en', browser, page} = {}) { | ||
if (!text) throw new Error('missing text') | ||
if (!from) throw new Error('missing from') | ||
if (!to) throw new Error('missing to') | ||
if (!browser) browser = await createBrowser({headless: false, screenshot: true}) | ||
|
||
const translation = await page.evaluate(() => document.querySelector('[jsaction="copy:"] > div > div span > div > div > div > div > span').textContent) | ||
await page.close() | ||
await browser.instance.close() | ||
page = page || await browser.newPage() | ||
await page.goto(`https://translate.google.com/?op=translate&sl=${from}&tl=${to}&text=${encodeURIComponent(text)}`) | ||
await page.waitForSelector('[jsaction^="copy:"] div span[lang="ko"] span[jsaction^="click:"]', {timeout: 10000}) | ||
|
||
return translation | ||
const translation = await page.evaluate(() => [...document.querySelectorAll('[jsaction^="copy:"] div span[lang="ko"] span[jsaction^="click:"]')].map(e => e.textContent.trim()).filter(s => s !== 'Try again').join(' ')) | ||
await page.close() | ||
await browser.instance.close() | ||
|
||
return translation | ||
} | ||
|
||
module.exports = translate |