有没有办法在节点的浏览器中打开 html

Is there a way to open html in a browser in node

在 python 的 scrapy 中有一种方法可以在浏览器中呈现 html (https://docs.scrapy.org/en/latest/topics/debug.html#open-in-browser)。

我目前正在 node 中工作并进行一些抓取。

var req = http.request(options, function (res) {
   var chunks = [];
   res.on("data", function (chunk) {
       chunks.push(chunk);
   });

   res.on("end", function () {
       var body = Buffer.concat(chunks);
       console.log(body.toString());
   });
});

req.end();

我可以获得抓取的 html 页面,并希望在调试时在浏览器中呈现它。在节点中完成此操作的最佳方法是什么?

举个例子,我想在正文声明之后和 REPL 运行 中设置一个断点,例如:

open_in_browser(body.toString())

就像在 scrapy 中一样。

在不使用 Puppeteer 的情况下,您可以使用 chrome-launcher, then use chrome-remote-interface 与 chrome 调试端口交互,您可以调用一个方法来设置页面内容。

例如,

function scrape_content() {
    const http = require('https')

    const options = {
        hostname: 'whosebug.com',
        port: 443,
        path: '/questions/71363220/is-there-a-way-to-open-html-in-a-browser-in-node',
        method: 'GET'
    }

    const req = http.request(options, function (res) {
        const chunks = []
        res.on("data", chunk => chunks.push(chunk))
        res.on("end", () => open_content_in_chrome(Buffer.concat(chunks).toString()))
    })

    req.end()
}

scrape_content()

async function open_content_in_chrome(content) {
    const ChromeLauncher = require('chrome-launcher')

    const chrome = await ChromeLauncher.launch()

    console.log(`Chrome debugging port running on ${chrome.port}`)

    const CDP = require('chrome-remote-interface')

    let client
    try {
        // connect to chrome debugging port
        client = await CDP({
            port: chrome.port
        })

        const { Page } = client

        const { frameId } = await Page.navigate({ url: 'about:blank' })
        await Page.setDocumentContent({ frameId, html: content })

    } catch (err) {
        console.error(err)
    } finally {
        if (client) {
            await client.close()
        }
    }
}