0

From what I gathered, it is indeed possible to call a JS function from python (using js2py for example).
However, is it possible to do that when the JS code depends on additional libraries?

JS code:

const puppeteer = require('puppeteer');

async function shorturl(link) {
    const browser = await puppeteer.launch({ headless: true });
    const page = await browser.newPage();
    await page.goto("https://www.shorturl.at", { waitUntil: 'networkidle0' });

    await page.waitForSelector('input[name=u]');
    await page.$eval('input[name=u]', (el, value) => el.value = value, link);
    await page.click('input[type="submit"]');
    // await page.waitForNavigation();
    await page.waitForSelector('#shortenurl');

    const result = await page.evaluate(() => {
        const anchor = document.querySelector('#shortenurl').value;
        return anchor;
    });

    console.log(result);
    await browser.close();

    return result;
};

My main goal is to allow python to execute a JS script that is meant to extract a short URL link from a website.
It took me a while to figure out how to perform that task with JS.
If I have to, I'll try to find a way to execute the same thing in python.

Sleeper
  • 47
  • 4
  • 2
    Since this is just a couple of lines of code, it will be much easier to rewrite it on python using [pyppeteer](https://github.com/pyppeteer/pyppeteer). – Olvin Roght Sep 01 '21 at 10:19
  • Pyppeteer or Selenium is the best approach, very likely, but failing that you can run Node in a subprocess from Python and capture the result programmatically (write to a file or stdout) -- it's the same as running Node any other way, pretty much. – ggorlen Sep 01 '21 at 15:19
  • Does this answer your question? [How to suppress or capture the output of subprocess.run()?](https://stackoverflow.com/questions/41171791/how-to-suppress-or-capture-the-output-of-subprocess-run) (replace the `ls` command with `node`) – ggorlen Sep 01 '21 at 15:20

0 Answers0