将jquery注入puppeteer页面
我正在尝试将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
工作示例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(); })();
我这样做:
await page.addScriptTag({ url: 'https://code.jquery.com/jquery-3.2.1.min.js' }); const title = await page.evaluate(() => { const $ = window.$; //otherwise the transpiler will rename it and won't work return $('h1 > span').text(); });
对于那些想要注入jQuery的本地副本的人:
await page.addScriptTag({path: require.resolve('jquery')})
这对我有用。
async function inject_jquery(page){ await page.evaluate(() => { var jq = document.createElement("script") jq.setAttribute('type','text/javascript'); jq.src = "https://code.jquery.com/jquery-3.2.1.min.js" return new Promise( (resolve) => { jq.addEventListener("load", ()=> { resolve(); }); document.getElementsByTagName("head")[0].appendChild(jq); }); }) const watchDog = page.waitForFunction('window.jQuery !== undefined'); await watchDog; }
有些网站不允许您注入脚本标记,因此您必须在允许之前注入其内容。 如果是这种情况,您可以使用evaluate
方法从CDN获取脚本内容并手动注入它们:
const jquery = await page.evaluate(() => window.fetch('https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js').then((res) => res.text())); await page.goto(YOUR_PAGE_HERE); await page.evaluate(jquery);
如果你想在野外看到一个例子,这用于在这里抓取puppeteer的无浏览器文档。