Puppeteer无法显示完整的SVG图表

问题描述 投票:0回答:1

我在Try Puppeteer中使用此代码:

const browser = await puppeteer.launch();

const page = await browser.newPage();
await page.goto('https://www.barchart.com/futures/quotes/ESM19/interactive-chart/fullscreen');

const linkHandlers = await page.$x("//li[contains(text(), '1D')]");

if (linkHandlers.length > 0) {
  await linkHandlers[0].click();
} else {
  throw new Error("Link not found");
}

await page.$eval('input[name="fieldInput"]', el => el.value = '1');

console.log(await page.content())
// const text = page.evaluate(() => document.querySelector('rect'))
// text.then((r) => {console.log(r[0])})

await page.screenshot({path: 'screenshot.png'});

await browser.close();

Chrome浏览器中加载的同一页面会显示指示价格变动的条形图,但在Puppeteer中获取的屏幕截图中,图表为空。

此外,page.content()提供的html与我在Chrome中检查元素时看到的完全不同。

javascript node.js web-scraping puppeteer
1个回答
2
投票

问题

在输入更改时,您不会等待请求解决。由于更改将触发请求,您应该使用page.waitForResponse等待数据加载。

另外,这是一个Angular应用程序,如果您只是通过el.value = '1'更改字段的值,它似乎不喜欢它。相反,你需要尝试更像人类(并点击退格键并输入输入值)。

首先,从文档中获取元素句柄(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函数并将其替换为page.waitForXPath函数。这可确保您的脚本在页面加载之前等待,并且在脚本继续之前,您要单击的元素可用。

© www.soinside.com 2019 - 2024. All rights reserved.