如何在 Puppeteer 中执行 JavaScript 代码

4

我对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: 无法设置null的'value'属性


似乎 #LandingAirBookingSearchForm_originationAirportCode 不在 DOM 中。你确认过了吗? - Ruan Mendes
我通过访问该网站并执行该脚本进行了手动检查。 - Valip
不要手动操作,运行 await page.evaluate("document.getElementById('LandingAirBookingSearchForm_originationAirportCode'),这应该返回 null,这意味着你需要等待它。 - Ruan Mendes
那就是说没有办法一次性运行像示例中的js代码吗? - Valip
不确定您的意思;JavaScript正在运行。但它是在元素创建之前运行的。 - Ruan Mendes
1个回答

4
  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 代码来自用户输入,这意味着它可以包含任何内容,我不确定是否可能解析出每个代码块并执行此模式。 - Valip
在这种情况下,请忘记我的第一个观点...但您仍然需要等待页面完全加载,以便您可以实际选择和操作元素。请参阅此处:https://dev59.com/C1QK5IYBdhLWcg3wF8B6#52501267 - Mischa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接