我正在尝试将jquery注入我的puppeteer页面,因为document.querySelector不会为我剪切它:
async function inject_jquery(page){ await page.evaluate(() => { var jq = document.createElement("script") jq.src = "https://code.jquery.com/jquery-3.2.1.min.js" document.querySelector("head").appendChild(jq) }) const watchDog = page.waitForFunction('window.jQuery !== undefined'); await watchDog; }
结果是它大部分时间超时.有没有人有办法解决吗?
解决方法
我使用page.addScriptTag来注入js文件.
... await page.addScriptTag({url: 'https://code.jquery.com/jquery-3.2.1.min.js'}) ...
page.addScriptTag – 文档
使用puppeteer的工作示例:0.12.0
import { launch } from 'puppeteer' (async () => { const browser = await launch({headless: false}); const page = await browser.newPage(); await page.goto('https://example.com',{waitUntil: 'networkidle'}); await page.addScriptTag({url: 'https://code.jquery.com/jquery-3.2.1.min.js'}); await page.close(); await browser.close(); })();