從 api 接收 html 后,我正在做一些抓取。我想做以下事情:
- 在 chrome 中打開 html 頁面,以便我可以在控制臺中找到選擇器。
- 立即將相同的 html 頁面加載到 jsdom 實體中
- 進入 repl - 然后我可以在控制臺中找到正確的選擇器并在實時 jsdom 環境中測驗它們以查看它們是否有效。
對于 1,我有:
async function openHtml(htmlString) {
const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
await page.setContent(htmlString);
return;
// await browser.close();
}
api提供的代碼是:
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);
response = JSON.parse(body); //response.content = html, response.cookies = cookies
const dom = new JSDOM(response.content);
console.log(dom.window.document.querySelector("p").textContent); // "Hello world"
openHtml(response.content);
console.log('hi');
});
});
req.end();
如果我在命令列運行代碼,瀏覽器會按預期打開。但是,如果我在以下位置設定斷點:
console.log('hi');
它不是。我怎樣才能得到這個作業?
uj5u.com熱心網友回復:
openHtml是一個異步函式。因此,您還必須將 await (promise) 和 main 函式中的呼叫方法設定為異步。
var req = http.request(options, function (res) {
var chunks = []
res.on('data', function (chunk) {
chunks.push(chunk)
})
res.on('end', async function () {
var body = Buffer.concat(chunks)
response = JSON.parse(body) //response.content = html, response.cookies = cookies
const dom = new JSDOM(response.content)
console.log(dom.window.document.querySelector('p').textContent) // 'Hello world'
await openHtml(response.content)
console.log('hi')
})
})
req.end()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/442714.html
標籤:javascript 节点.js 异步 傀儡师 jsdom
