【问题标题】:How to execute a javascript code in puppeteer如何在 puppeteer 中执行 javascript 代码
【发布时间】:2020-02-24 20:18:20
【问题描述】:

我是 puppeteer 的新手,并试图弄清楚如何在 puppeteer 中以字符串值的形式执行 JavaScript 代码。

例如,值(从输入中检索)可能如下所示:document.getElementById('selector').value='some_value';

我已经实现了以下代码

const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://www.southwest.com/', { waitUntil: 'domcontentloaded' });
const script = await page.evaluate("document.getElementById('LandingAirBookingSearchForm_originationAirportCode').value='Dallas'; document.getElementById('LandingAirBookingSearchForm_originationAirportCode').dispatchEvent(new Event('input',{bubbles:!0}));");
await browser.close();

但它返回以下错误:

评估失败:TypeError:无法设置属性“值”为空

【问题讨论】:

  • 似乎#LandingAirBookingSearchForm_originationAirportCode不在DOM中。你验证了吗?
  • 我通过访问该站点并执行该脚本手动检查了它
  • 不是手动,运行await page.evaluate("document.getElementById('LandingAirBookingSearchForm_originationAirportCode')应该返回null,这意味着你必须等待它。
  • 意味着没有办法像示例中的那样一次运行 js 代码?
  • 不确定你的意思; JavaScript 正在运行。但它在创建元素之前运行。

标签: javascript node.js puppeteer


【解决方案1】:
  1. 在回调中评估页面上的脚本
  2. 在执行脚本之前等待 ID 为“LandingAirBookingSearchForm_originationAirportCode”的元素,以确保侧面已加载
const puppeteer = require('puppeteer');

(async function () {
    const browser = await puppeteer.launch(/*{headless: false}*/);
    const page = await browser.newPage();
    await page.goto('https://www.southwest.com/', { waitUntil: 'domcontentloaded' });
    await page.waitFor('#LandingAirBookingSearchForm_originationAirportCode');
    await page.evaluate(() => {
        document.getElementById('LandingAirBookingSearchForm_originationAirportCode').value='Dallas'; 
        document.getElementById('LandingAirBookingSearchForm_originationAirportCode').dispatchEvent(new Event('input',{bubbles:!0}));
    });
    await browser.close();
})();

【讨论】:

  • javascript 代码来自用户输入,这意味着它可以包含任何内容,我不确定是否可以解析每个代码块并执行此模式
  • 在这种情况下忘记我的第一点....但是您仍然必须等待页面完全加载,以便您可以实际选择和操作元素。看看这里:stackoverflow.com/questions/52497252/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-10
  • 2011-10-01
  • 1970-01-01
相关资源
最近更新 更多