Problem
当输入更改时,您不会等待请求得到解决。由于更改会触发请求,因此您应该使用page.waitForResponse https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pagewaitforresponseurlorpredicate-options等待数据加载。
此外,这是一个 Angular 应用程序,如果您只是通过以下方式更改字段的值,它似乎不喜欢它el.value = '1'
。相反,您需要尝试表现得更像人类(然后按退格键并键入输入值)。
Solution
首先,您获得元素句柄(input[name="fieldInput"
)来自文档。然后,聚焦该元素,按退格键删除其中的值。之后,您键入所需的输入值。
输入字段现在具有正确的值,现在我们需要触发blur通过调用事件blur()
在元素上。同时,我们等待对服务器的请求完成。请求完成后,我们应该给页面几毫秒的时间来呈现数据。
总之,生成的代码如下所示:
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://www.barchart.com/futures/quotes/ESM19/interactive-chart/fullscreen');
// wait until the element appears
const linkHandler = await page.waitForXPath("//li[contains(text(), '1D')]");
await linkHandler.click();
// get the input field, focus it, remove what's inside, then type the value
const elementHandle = await page.$('input[name="fieldInput"]');
await elementHandle.focus();
await elementHandle.press('Backspace');
await elementHandle.type('1');
// trigger the blur event and wait for the response from the server
await Promise.all([
page.waitForResponse(response => response.url().includes('https://www.barchart.com/proxies/timeseries/queryminutes.ashx')),
page.evaluate(el => el.blur(), elementHandle)
]);
// give the page a few milliseconds to render the diagram
await page.waitFor(100);
await page.screenshot({path: 'screenshot.png'});
await browser.close();
代码改进
我还删除了page.$x https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pagexexpression函数并将其替换为page.waitForXPath https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pagewaitforxpathxpath-options功能。这可确保您的脚本等待页面加载并且您要单击的元素可用,然后脚本才会继续。