如何在木偶中执行javascript代码 [英] How to execute a javascript code in puppeteer

查看:41
本文介绍了如何在木偶中执行javascript代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是木偶新手,正在尝试了解如何执行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"

推荐答案

  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代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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