javascript - 如何在 puppeteer 中加载脚本?

标签 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)
  })
})()
但是当我尝试执行 axios.get它返回 Evaluation failed: ReferenceError: axios is not defined .这里有什么问题?

最佳答案

使用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
});

关于javascript - 如何在 puppeteer 中加载脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65332062/

相关文章:

javascript - 泛型类的 TypeScript 数组

javascript - Highcharts基本条: How to know which specific bar section is clicked?

javascript - jquery-autocomplete:serviceUrl来过滤lookupFilter()中显示的结果

javascript - Puppeteer 元素点击坐标片状

Javascript 总返回 NaN 为 4 位数字

javascript - 在站点导航时保持 WebRTC 视频流处于事件状态

puppeteer - 表情符号在 Chrome Headless 的 PDF 输出中转换为灰色

google-chrome - puppeteer/ headless Chrome 在阿尔卑斯字体问题

javascript - Puppeteer:等到 elementHandle 不再附加到 DOM

javascript - Puppeteer 抛出无效参数错误