将jquery注入puppeteer页面

pgu*_*rio 18 jquery node.js 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;
}
Run Code Online (Sandbox Code Playgroud)

结果是它大部分时间超时.有没有人有办法解决吗?

nil*_*arp 33

我习惯于page.addScriptTag注入js文件.

...
await page.addScriptTag({url: 'https://code.jquery.com/jquery-3.2.1.min.js'})
...
Run Code Online (Sandbox Code Playgroud)

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();
})();
Run Code Online (Sandbox Code Playgroud)


小智 16

对于那些想要注入jQuery的本地副本的人:

await page.addScriptTag({path: require.resolve('jquery')})

  • 现在可以使用:await page.addScriptTag({path: 'myScript.js'}) (2认同)

Tud*_*rar 12

我这样做:

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();
});
Run Code Online (Sandbox Code Playgroud)


bro*_*ess 6

有些网站不允许您注入脚本标记,因此您必须先注入它的内容,然后它才会允许您这样做。如果是这种情况,您可以使用该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);
Run Code Online (Sandbox Code Playgroud)

如果您想查看野外示例,则可以在此处抓取 puppeteer 的无浏览器文档(我是该工具的作者)。