如何在 puppeteer 中加载脚本?

Leo*_*Leo 6 javascript puppeteer

我正在尝试使用 puppeteer 在 chromium 中加载 axios,代码如下:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({headless:false})
  const page = await browser.newPage()
  await page.goto('https://httpbin.org/get')
  await page.evaluate(async () => {
    var script = document.createElement('script');
    script.setAttribute('src','https://unpkg.com/axios@0.21.0/dist/axios.min.js');
    document.head.appendChild(script);
    var r = await axios.get('https://httpbin.org/get')
    console.log(r)
  })
})()
Run Code Online (Sandbox Code Playgroud)

但是当我尝试执行时axios.get它会返回Evaluation failed: ReferenceError: axios is not defined. 这里有什么问题?

Vav*_*off 6

为此使用page.addScriptTag :

await page.goto('https://example.com');

await page.addScriptTag({ url: 'https://unpkg.com/axios@0.21.0/dist/axios.min.js' }); 

const data = await page.evaluate(async () => {
  const response = await axios.get('https://httpbin.org/get')
  return response.data; // <-- this is important: the whole response cannot be returned
});
Run Code Online (Sandbox Code Playgroud)