如何在木偶中执行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"
解决方案
- 在回调中评估页面上的脚本
- 等待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();
})();
相关文章