如何在 puppeteer 中加载脚本? [英] How to load script in puppeteer?

查看:115
本文介绍了如何在 puppeteer 中加载脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

推荐答案

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

这篇关于如何在 puppeteer 中加载脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆