How to load script in puppeteer?

蓝咒 提交于 2021-02-10 16:08:16

问题


I'm trying to load axios in chromium using puppeteer, the code is as follows:

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)
  })
})()

But when I try to execute axios.get it returns Evaluation failed: ReferenceError: axios is not defined. What's the issue here?


回答1:


Use page.addScriptTag for this:

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


来源:https://stackoverflow.com/questions/65332062/how-to-load-script-in-puppeteer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!